题目

删除链表的倒数第 N 个结点 - 图1

解题思路

快慢指针法。

由于我们需要找到倒数第 n 个节点,初始时 first 和second 均指向头节点。我们首先使用first 对链表进行遍历,遍历的次数为 n。此时,first 和 second 之间间隔了 n−1 个节点,即first 比 second 超前了 n 个节点。

在这之后,我们同时使用 first 和 second 对链表进行遍历。当 first 遍历到链表的末尾(即 first 为空指针)时,second 恰好指向倒数第 n 个节点。

当 first 遍历到链表的末尾时,second 的下一个节点就是我们需要删除的节点。

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode removeNthFromEnd(ListNode head, int n) {
  13. ListNode dummy = new ListNode(0, head);
  14. ListNode first = head;
  15. ListNode second = dummy;
  16. for (int i = 0; i < n; ++i) {
  17. first = first.next;
  18. }
  19. while (first != null) {
  20. first = first.next;
  21. second = second.next;
  22. }
  23. second.next = second.next.next;
  24. ListNode ans = dummy.next;
  25. return ans;
  26. }
  27. }