diff --git a/typescript/19-Remove-Nth-Node-From-End-of-List.ts b/typescript/19-Remove-Nth-Node-From-End-of-List.ts index c9e2b6400..24268c9fb 100644 --- a/typescript/19-Remove-Nth-Node-From-End-of-List.ts +++ b/typescript/19-Remove-Nth-Node-From-End-of-List.ts @@ -11,25 +11,21 @@ */ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { - let dummyList: ListNode = new ListNode(0) - dummyList.next = head - let count: number = 0 - let first: ListNode = dummyList - let second: ListNode = dummyList - - while (count < n) { - second = second.next - count++ - } - if (second === null) { - dummyList.val = dummyList.next.val - dummyList.next = dummyList.next.next - } - while (second.next !== null) { - second = second.next - first = first.next - } - first.next = first.next.next - - return dummyList.next -} + let dummy: ListNode = new ListNode(0, head) + let left = dummy + let right = head + + while (n > 0) { + right = right.next + n -= 1 + } + + while (right) { + left = left.next + right = right.next + } + + // delete + left.next = left.next.next + return dummy.next +};