File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments