19. Remove Nth Node From End of List

  • Source : Link
  • Author : Han
  • Date : 2022-02-09

Problems

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

Example 1:

https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg

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

Example 2:

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

Example 3:

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 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 map = mutableMapOf<Int, ListNode?>()
        var node = head
        var size = 1
        while (node?.next != null) {
            map[size] = node
            node = node.next
            size += 1
        }

        if(map[size - n] == null)
            return map[size - n + 1]?.next
        else
            map[size - n]?.next = map[size - n + 1]?.next

        return head
    }
}