forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0019-remove-nth-node-from-end-of-list.java
40 lines (33 loc) · 1.13 KB
/
0019-remove-nth-node-from-end-of-list.java
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
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
// Using Two Pointer Approach:
// Take a pointer second and put it at (n+1)th position from the beginning
// Take pointer first and move it forward till second reaches Last Node and second.next points to null
// At that point we would have reached the (n-1)th node from the end using the pointer first
// Unlink or Skip that node
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || head.next == null) return null;
ListNode temp = new ListNode(0);
temp.next = head;
ListNode first = temp, second = temp;
while (n > 0) {
second = second.next;
n--;
}
while (second.next != null) {
second = second.next;
first = first.next;
}
first.next = first.next.next;
return temp.next;
}
}