Skip to content
This repository was archived by the owner on Sep 8, 2025. It is now read-only.

Commit d53223c

Browse files
authored
remove-nth-node-from-end-of-list (#7)
1 parent 0341ea1 commit d53223c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

0 commit comments

Comments
 (0)