1. 题目
链接
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
2. 思路
这题的解法很多,我采用的是用快慢指针的方式。
快指针先走n
然后快慢指针一起走,直到快指针走到尾节点.
此时的慢指针指向的就是倒数的n+1个节点.
3. 题解
代码如下
/**
* 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 static ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || n <= 0)
return head;
if (head.next == null) {
if (n == 1)
return null;
return head;
}
ListNode fast = head;
ListNode slow = head;
for(int i = 0; i < n; i++ ){
fast = fast.next;
}
//如果fast == null,则代表要删除的节点为第一个。
if(fast == null){
return head.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
我们可以看一看slow是不是指向的是倒数n+1节点:
我们要删除的是倒数第二个节点,其值为4。返回的slow的第一个节点的值为3,则表明slow指向的就是倒数n+1个节点