给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
似乎有个循环链表找出口的题也是这种思路,快慢指针找到固定长度的位置。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//虚拟节点与快慢指针
ListNode dummy = new ListNode(0, head);
ListNode slow = dummy;
ListNode fast = dummy;
//fast指针先走n+1步
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
//快慢指针一起移动,fast为空时,
//slow刚好在待删除结点的前一个位置
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
//删除
slow.next = slow.next.next;
//返回
return dummy.next;
}
}class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//虚拟节点与快慢指针
ListNode dummy = new ListNode(0, head);
ListNode slow = dummy;
ListNode fast = dummy;
//fast指针先走n+1步
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
//快慢指针一起移动,fast为空时,
//slow刚好在待删除结点的前一个位置
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
//删除
slow.next = slow.next.next;
//返回
return dummy.next;
}
}