Skip to content

Commit

Permalink
Feat: 19. Remove Nth Node From End of List
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Oct 28, 2024
1 parent 04c02d7 commit e808b1a
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions remove-nth-node-from-end-of-list/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}

/**
* https://leetcode.com/problems/remove-nth-node-from-end-of-list
* T.C. O(N)
* S.C. O(1)
*/
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
let first = head;
let second = head;

for (let i = 0; i < n; i++)
first = first!.next;

if (!first)
return head!.next;

while (first.next) {
first = first.next;
second = second!.next;
}

second!.next = second!.next!.next;

return head;
}

0 comments on commit e808b1a

Please sign in to comment.