LeetCode 19. 删除链表的倒数第N个节点
原题链接
中等
作者:
LangB
,
2020-10-28 15:22:14
,
所有人可见
,
阅读 288
快慢指针
/**
* 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 dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
// 让快指针先n步
while (n-- > 0) {
fast = fast.next;
}
// 快慢指针同时往前移动,直至快指针到链表末尾
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
// 删除第 n 个节点
slow.next = slow.next.next;
return dummy.next;
}
}