Open Zheaoli opened 1 year ago
/*
* @lc app=leetcode id=19 lang=typescript
*
* [19] Remove Nth Node From End of List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
const dummy = new ListNode(0, head);
// the distance between left and right is always n
let left = dummy;
let right = head;
for (let i = 0; i < n; i++) {
right = right.next;
}
// right will reach the end of this list
// and left would be the prev node of target node that we need to delete
while (right) {
left = left.next;
right = right.next;
}
// delete the node
left.next = left.next.next;
return dummy.next;
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-10-13