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
        }
    }
    
  • 相关阅读:
    【u026】花园(garden)
    【BZOJ 1040】[ZJOI2008]骑士
    【t100】汤姆斯的天堂梦
    【BZOJ 1038】[ZJOI2008]瞭望塔
    【t096】树的序号
    Java Web整合开发(82)
    2 HTML解析
    T3186 队列练习2 codevs
    T3185 队列练习1 codevs
    T1191 数轴染色 codevs
  • 原文地址:https://www.cnblogs.com/zhongju/p/14095995.html
Copyright © 2011-2022 走看看