MrainW's Home

All things come to those who wait!

0%

LeetCode 19. Remove Nth Node From End of List

Question

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

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy, second = dummy;
for (int i = 1; i <= n+1; i++)
first = first.next;
while(first != null){
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels