File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ //LeetCode 19. Nth Node From End of List
2+ //Question - https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
4+ /**
5+ * Definition for singly-linked list.
6+ * public class ListNode {
7+ * int val;
8+ * ListNode next;
9+ * ListNode() {}
10+ * ListNode(int val) { this.val = val; }
11+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12+ * }
13+ */
14+ class Solution {
15+ public ListNode removeNthFromEnd (ListNode head , int n ) {
16+ //dummy is needed when the node to be deleted is the first node
17+ //In this case, the fast pointer would point to null after completing the for loop
18+ //As a result the while loop is not activated and slow remains at the dummy node.
19+ ListNode dummy = new ListNode ();
20+ dummy .next = head ;
21+ ListNode fast = dummy ;
22+ ListNode slow = dummy ;
23+
24+ //Make the fast pointer point to a location just after the nth node to be deleted
25+ for (int i = 1 ; i <= n + 1 ; i ++){
26+ fast = fast .next ;
27+ }
28+
29+ while (fast != null ){
30+ fast = fast .next ;
31+ slow = slow .next ;
32+ }
33+
34+ slow .next = slow .next .next ;
35+ return dummy .next ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments