[leetcode - Bliend-75 ] 19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

给一个 linked list 并移除倒数第 n 个 node。

Example

Input: 1 -> 2 -> 3 -> 4 -> 5, n = 2;
Output: 1 -> 2 -> 3 -> 5

Step

利用快慢双指针,建立一个 node 连在 head 前面并让慢指针指向 node
http://img2.58codes.com/2024/20124767099QuTyiDX.jpg
http://img2.58codes.com/2024/20124767RP29Y2FHoa.jpg

设定慢指针与快指针
http://img2.58codes.com/2024/20124767twt57FEBeB.jpg

让快指针先跑 n 个 node,再让两个指针一起跑,跑到快指针抵达 head 的最后一个 node,这样就会使慢指针刚好停在要被移除的 node 的前一个 node。
http://img2.58codes.com/2024/rjcf3FG.gif

将慢指针指到的 node 连接到下下个 node
http://img2.58codes.com/2024/20124767WVTWRbABmx.jpg

Coding

/** * @param {ListNode} head * @param {number} n * @return {ListNode} */var removeNthFromEnd = function(head, n) {    if(head == null) return head;     var node = new ListNode(0);    node.next = head;    let slow = node;    let fast = head;    while (n > 0) {        fast = fast.next;        n--;    }    while(fast){        fast = fast.next;        slow = slow.next;    }    if(slow.next === null){        slow.next = null ;    } else {        slow.next = slow.next.next;    }    return node.next;};

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章