Skip to content

Commit a74d56c

Browse files
committed
feat: remove-nth-node-from-end-of-list
1 parent 69f4a44 commit a74d56c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">week12-2. remove-nth-node-from-end-of-list</a>
3+
* <li>Description: Given the head of a linked list, remove the nth node from the end of the list and return its head</li>
4+
* <li>Topics: Linked List, Two Pointers </li>
5+
* <li>Time Complexity: O(N), Runtime 0ms </li>
6+
* <li>Space Complexity: O(1), Memory 41.95MB </li>
7+
*/
8+
class Solution {
9+
public ListNode removeNthFromEnd(ListNode head, int n) {
10+
ListNode dummy = new ListNode(0, head);
11+
ListNode fast = dummy;
12+
ListNode slow = dummy;
13+
14+
for(int i=0; i<=n; i++){
15+
fast = fast.next;
16+
}
17+
18+
while (fast != null) {
19+
slow = slow.next;
20+
fast = fast.next;
21+
}
22+
23+
slow.next = slow.next.next;
24+
25+
return dummy.next;
26+
}
27+
}

0 commit comments

Comments
 (0)