Leetcode19. Remove Nth Node From End of List

Leetcode19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note: Given n will always be valid.

Follow up:
Could you do this in one pass?

解析

设想假设设定了双指针 pq 的话,当 q 指向末尾的 NULLpq 之间相隔的元素个数为 n 时,那么删除掉p 的下一个指针就完成了要求。

  • 设置虚拟节点 dummyHead 指向 head
  • 设定双指针 pq,初始都指向虚拟节点dummyHead
  • 移动 q,直到 pq 之间相隔的元素个数为 n
  • 同时移动 pq,直到q指向的为 NULL
  • p 的下一个节点指向下下个节点
    Leetcode19. Remove Nth Node From End of List

Java

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode first = dummy;
    ListNode second = dummy;
    // Advances first pointer so that the gap between first and second is n nodes apart
    for (int i = 1; i <= n + 1; i++) {
        first = first.next;
    }
    // Move first to the end, maintaining the gap
    while (first != null) {
        first = first.next;
        second = second.next;
    }
    second.next = second.next.next;
    return dummy.next;
}
Leetcode19. Remove Nth Node From End of ListLeetcode19. Remove Nth Node From End of List magic_jiayu 发布了19 篇原创文章 · 获赞 2 · 访问量 2879 私信 关注
上一篇:【每日算法/刷穿 LeetCode】24. 两两交换链表中的节点(中等)


下一篇:PHP 页面静态化/纯静态化/伪静态化