This repository was archived by the owner on Sep 8, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-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
+ * public int val;
5
+ * public ListNode next;
6
+ * public ListNode(int val=0, ListNode next=null) {
7
+ * this.val = val;
8
+ * this.next = next;
9
+ * }
10
+ * }
11
+ */
12
+ public class Solution
13
+ {
14
+ // Returns a ListNode
15
+ public ListNode RemoveNthFromEnd ( ListNode head , int n )
16
+ {
17
+ ListNode dummy = new ListNode ( - 1 ) ;
18
+ dummy . next = head ;
19
+ ListNode slow = dummy , fast = dummy ;
20
+
21
+ for ( int i = 0 ; i < n ; i ++ )
22
+ {
23
+ fast = fast . next ;
24
+ }
25
+
26
+ while ( fast . next != null )
27
+ {
28
+ slow = slow . next ;
29
+ fast = fast . next ;
30
+ }
31
+
32
+ slow . next = slow . next . next ;
33
+
34
+ return dummy . next ;
35
+ }
36
+ }
37
+
38
+ /** SOLUTION TWO **/
39
+
40
+ public class Solution {
41
+ public ListNode RemoveNthFromEnd ( ListNode head , int n ) {
42
+ ListNode current = head ;
43
+ Dictionary < int , ListNode > nodePositions = new ( ) ;
44
+
45
+ int i = 0 ;
46
+ while ( current != null ) {
47
+ nodePositions [ i ] = current ;
48
+ current = current . next ;
49
+ i ++ ;
50
+ }
51
+
52
+ if ( i - n == 0 ) {
53
+ return head . next ;
54
+ }
55
+
56
+ nodePositions [ i - n - 1 ] . next = nodePositions [ i - n ] . next ;
57
+
58
+ return head ;
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments