From f71a43b15657de4780c21ad9b5ba211655a9b0f0 Mon Sep 17 00:00:00 2001 From: Shahriar Shatil <52494840+ShatilKhan@users.noreply.github.com> Date: Sun, 3 Mar 2024 22:32:48 +0600 Subject: [PATCH] Time: 56 ms (58.72%) | Memory: 50.9 MB (15.73%) - LeetSync --- .../remove-nth-node-from-end-of-list.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js diff --git a/19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js b/19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js new file mode 100644 index 0000000..fe9476c --- /dev/null +++ b/19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function(head, n) { + // Create a dummy node to handle cases where the head is removed + const dum = new ListNode(0); + dum.next = head; + + // Initialize two pointers: first and second + let first = dum; + let scnd = dum; + + // Move the first pointer n nodes ahead of the second pointer + for ( let i = 0; i < n + 1; i++){ + first = first.next; + } + while(first !== null){ + first = first.next; + scnd = scnd.next; + } + + // Remove the nth node from the end by adjusting pointers + scnd.next = scnd.next.next; + + // Return the head of the modified linked list + return dum.next; +}; \ No newline at end of file