Skip to content

Commit 468727c

Browse files
authored
Merge pull request #136 from SaimantikaBasu/patch-3
Update 19.java
2 parents 81c56cf + c414ddf commit 468727c

File tree

1 file changed

+22
-31
lines changed

1 file changed

+22
-31
lines changed

leetcode/java/linkedlist/19.java

Lines changed: 22 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -10,37 +10,28 @@
1010
*/
1111
class Solution {
1212
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;
13+
if(n==0 || head==null)
14+
return head;
15+
if(n==1 && head.next==null)
16+
return null;
1717

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;
18+
ListNode fast=head;
19+
ListNode slow=head;
20+
while(n-->0)
21+
fast=fast.next;
22+
if(fast==null)
23+
return slow.next;
24+
while(fast.next!=null)
25+
{
26+
fast=fast.next;
27+
slow=slow.next;
28+
}
29+
30+
ListNode fwd=slow.next;
31+
slow.next=fwd.next;
32+
fwd.next=null;
33+
34+
return head;
4435
}
4536

46-
}
37+
}

0 commit comments

Comments
 (0)