Loading

[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
    }
}
posted @ 2020-12-07 10:49  Zhongju.copy()  阅读(66)  评论(0编辑  收藏  举报