Skip to content

Commit 612595a

Browse files
committed
Remove Nth Node From End Of List
1 parent 5f1ed68 commit 612595a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// TC: O(n)
2+
// Visit all elements in the worst case
3+
// SC: O(1)
4+
// Keep using ready assigned variables only
5+
class Solution {
6+
public ListNode removeNthFromEnd(ListNode head, int n) {
7+
ListNode output = new ListNode(0, head);
8+
ListNode dummy = output;
9+
10+
for (int i = 0; i < n; i++) head = head.next;
11+
12+
while (head != null) {
13+
head = head.next;
14+
dummy = dummy.next;
15+
}
16+
17+
dummy.next = dummy.next.next;
18+
19+
return output.next;
20+
}
21+
}

0 commit comments

Comments
 (0)