zoukankan      html  css  js  c++  java
  • [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 个节点,这样使得 slow 和 fast 之间有 N 个节点的距离。然后同时让 slow 和 fast 前移,直到 fast 遍历到链表尾部。此时此刻 slow 停下来的位置就是需要移除的节点之前的那个节点。代码中如果 for loop 分不清到底是 < N还是 <= N,可以找个 case 遍历一下即可。

    时间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() {}
     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);
    14         ListNode slow = dummy;
    15         ListNode fast = dummy;
    16         dummy.next = head;
    17         for (int i = 0; i <= n; i++) {
    18             fast = fast.next;
    19             // System.out.println(fast.val);
    20         }
    21         while (fast != null) {
    22             fast = fast.next;
    23             slow = slow.next;
    24         }
    25         slow.next = slow.next.next;
    26         return dummy.next;
    27     }
    28 }

    LeetCode 题目总结

  • 相关阅读:
    普通PC硬盘与DVR专用硬盘主要差别
    远程监控,需要安装控件,安装前对浏览器设置如下。硬盘录像机,采集卡通用...
    SQL Server不允许进行远程连接
    远程备份(还原)SQL2000数据库
    安装MSDE时提示 实例名无效
    冰雹,刨冰,危险人物
    北京首现最严重的0day攻击方式
    孤独,寂寞,无聊
    大家平时都在做什么
    华山之旅
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11817296.html
Copyright © 2011-2022 走看看