Skip to content

Commit 756b78f

Browse files
authored
Simply further
Further simplify solution, this also matches the python solution shown in the video.
1 parent 849251a commit 756b78f

File tree

1 file changed

+18
-23
lines changed

1 file changed

+18
-23
lines changed

typescript/19-Remove-Nth-Node-From-End-of-List.ts

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,21 @@
1111
*/
1212

1313
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
14-
let runner = head;
15-
let c = 0;
16-
17-
while (c != n && runner != null) {
18-
c++;
19-
runner = runner.next;
20-
}
21-
22-
if (runner == null) {
23-
return head.next;
24-
}
25-
26-
let tail = head;
27-
28-
while (runner.next != null) {
29-
runner = runner.next;
30-
tail = tail.next;
31-
}
32-
33-
tail.next = tail.next.next;
34-
35-
return head;
36-
}
14+
let dummy: ListNode = new ListNode(0, head)
15+
let left = dummy
16+
let right = head
17+
18+
while (n > 0) {
19+
right = right.next
20+
n -= 1
21+
}
22+
23+
while (right) {
24+
left = left.next
25+
right = right.next
26+
}
27+
28+
// delete
29+
left.next = left.next.next
30+
return dummy.next
31+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy