[LeetCode] 19. Remove Nth Node From End of List

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

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

移除链表倒数第N个节点。

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

思路是用两个 pointer slow 和 fast,先让 fast 前移 N + 1 个节点,这样使得 slow 和 fast 之间有 N + 1 个节点的距离。然后同时让 slow 和 fast 前移,直到 fast 遍历到链表尾部。此时此刻 slow 停下来的位置就是需要移除的节点之前的那个节点。为什么需要使 slow 和 fast 之间有 N + 1 个节点的距离是因为我们移除的是 slow.next 这个节点。可以参考这个动图帮助理解。

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * @param {ListNode} head
 3  * @param {number} n
 4  * @return {ListNode}
 5  */
 6 var removeNthFromEnd = function(head, n) {
 7     let dummy = new ListNode(0);
 8     let slow = dummy;
 9     let fast = dummy;
10     dummy.next = head;
11     for (let i = 0; i <= n; i++) {
12         fast = fast.next;
13     }
14     while (fast !== null) {
15         slow = slow.next;
16         fast = fast.next;
17     }
18     slow.next = slow.next.next;
19     return dummy.next;
20 };

 

Java实现

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

 

LeetCode 题目总结

posted @ 2019-11-08 01:20  CNoodle  阅读(408)  评论(0编辑  收藏  举报