forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathremove-nth-node-from-end-of-list.java
More file actions
33 lines (30 loc) · 955 Bytes
/
remove-nth-node-from-end-of-list.java
File metadata and controls
33 lines (30 loc) · 955 Bytes
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
/**
* 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; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode slow = head, fast = head, prev = null;
// move one ptr such that it points to nth node from start of Linked List
while(n-->1)
fast = fast.next;
// now move the second ptr as long as first ptr doesn't point to last node
while(fast.next!=null){
prev = slow;
slow = slow.next;
fast = fast.next;
}
// if the nth node from end is the start node of list
if(prev==null)
head = head.next;
else
prev.next = slow.next;
return head;
}
}