Skip to content

Commit 6f0b865

Browse files
committed
Added Leetcode solution in java to problem: Remove nth node from end in a linked list
1 parent 3ff1f5c commit 6f0b865

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

leetcode/java/linkedlist/19.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode removeNthFromEnd(ListNode head, int n) {
13+
ListNode dummy = new ListNode(0);
14+
dummy.next = head;
15+
ListNode first = dummy;
16+
ListNode second = dummy;
17+
18+
for (int i = 0; i < n; i++) {
19+
20+
// If count of nodes in the given
21+
// linked list is <= N
22+
if (second.next == null) {
23+
24+
// If count = N i.e. delete the head node
25+
if (i == n - 1)
26+
first = first.next;
27+
28+
}
29+
second = second.next;
30+
}
31+
32+
// Increment both the pointers by one until
33+
// second pointer reaches the end
34+
while (second.next != null) {
35+
first = first.next;
36+
second = second.next;
37+
}
38+
39+
// First must be pointing to the
40+
// Nth node from the end by now
41+
// So, delete the node first is pointing to
42+
first.next = first.next.next;
43+
return dummy.next;
44+
}
45+
46+
}

0 commit comments

Comments
 (0)