每日一题-Day31-删除链表的倒数第n个节点
作者:互联网
题目
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
解题思路
快慢指针:第一个指针先移动n个节点,然后两个指针同时开始移动,当第一个指针移动到链表的结尾节点时,第二个节点移动到倒数第n+1个节点,此时利用链表的性质即可删除倒数第n个节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp1 = head;
ListNode temp2 = head;
for (int i = 0; i < n; i++){
temp1 = temp1.next;
}
if (temp1 == null) {
return head.next;
}else {
while(temp1.next != null){
temp1 = temp1.next;
temp2 = temp2.next;
}
temp2.next = temp2.next.next;
}
return head;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
标签:head,ListNode,val,next,链表,temp1,Day31,倒数第 来源: https://www.cnblogs.com/cwtjyy/p/15588571.html