(LeetCode) 19. Remove Nth Node From End of List
Remove Nth Node From End of List
- Explore : Interview > Top Interveiw Questions > Easy Collection
- 분류 : Linked List
- 난이도 : Medium
Problem
Given the head
of a linked list, remove the n^th
node from the end of the list and return its head.
Example 1
1 2
| Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
|
Example 2
1 2
| Input: head = [1], n = 1 Output: []
|
Example 3
1 2
| 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
Solution
Exapnder
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 29 30 31 32 33 34 35 36 37
|
class Solution { fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { if (head?.next == null) { return null }
var first = head var current = head
var count = 0
while (count < n) { current = current?.next count++ }
while (current?.next != null) { first = first?.next current = current?.next }
if (first == head && current == null) { return first.next } first?.next = first?.next?.next return head } }
|
Point of Thinking
- 노드가 하나면 바로 null 반환처리
- n까지 index를 카운트한뒤 해당 index의 노드만 제거한 뒤 반환