zoukankan      html  css  js  c++  java
  • [LeetCode] 19. Remove Nth Node From End of List(从单链表中移除倒数第 n 个节点)

    Description

    Given the head of a linked list, remove the nth node from the end of the list and return its head.
    给定单链表的头节点 head,移除该链表的倒数第 n 个元素,返回 head

    Follow up

    Could you do this in one pass?
    你能仅用一次遍历解决它吗?

    Examples

    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

    Hint

    1. Maintain two pointers and update one with a delay of n steps.

    Solution

    这题的一个常规做法是先确定链表的大小,再去数倒数第 n 个节点,需要遍历两次。利用双指针法,维护两个间隔为 n 的指针,后一个指针指到 NULL 时,前一个指针便是要删除的位置。代码如下:

    /**
     * Example:
     * var li = ListNode(5)
     * var v = li.`val`
     * Definition for singly-linked list.
     * class ListNode(var `val`: Int) {
     *     var next: ListNode? = null
     * }
     */
    class Solution {
        fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
            val dummy = ListNode(-1)
            dummy.next = head
            var p: ListNode? = dummy
            var count = 0
            while (count <= n) {
                p = p?.next
                count++
            }
            
            var pre: ListNode? = dummy
            while (p != null) {
                pre = pre?.next
                p = p.next
            }
            
            pre?.next = pre?.next?.next
            
            return dummy.next
        }
    }
    
  • 相关阅读:
    拉普拉斯矩阵
    正定矩阵 和 半正定矩阵
    Random Walk
    论文解读(DGI)《DEEP GRAPH INFOMAX》
    python安装easyinstall/pip出错
    pip国内源设置
    在Jupyter Notebook添加代码自动补全功能
    [BUUCTF]PWN——bjdctf_2020_babystack2
    [BUUCTF]REVERSE——[BJDCTF 2nd]8086
    [BUUCTF]PWN——jarvisoj_tell_me_something
  • 原文地址:https://www.cnblogs.com/zhongju/p/14095995.html
Copyright © 2011-2022 走看看