We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent cc30fce commit 12ed6ebCopy full SHA for 12ed6eb
remove-nth-node-from-end-of-list/nhistory.js
@@ -0,0 +1,33 @@
1
+var removeNthFromEnd = function (head, n) {
2
+ // Edge case: If the list is empty
3
+ if (!head) return null;
4
+
5
+ // Create a dummy node that points to the head
6
+ let dummy = new ListNode(0);
7
+ dummy.next = head;
8
+ let length = 0,
9
+ curr = head;
10
11
+ // Calculate the length of the list
12
+ while (curr) {
13
+ length++;
14
+ curr = curr.next;
15
+ }
16
17
+ // Find the length-n node from the beginning
18
+ length = length - n;
19
+ curr = dummy;
20
+ while (length > 0) {
21
+ length--;
22
23
24
25
+ // Skip the desired node
26
+ curr.next = curr.next.next;
27
28
+ // Return the head, which may be a new head if we removed the first node
29
+ return dummy.next;
30
+};
31
32
+// TC: O(n)
33
+// SC: O(1)
0 commit comments