We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
由于不知道链表有几个节点,所以先建立一个数组,用来记录节点对应的下标顺序。
求倒数第 n 个,可以转化成求 正数的数组长度 - n 个,而通过数组又可以很容易的拿到待删除节点的前一个节点,那么就把前一个节点 prevNode.next = targetNode.next 这样更换指向即可。
倒数第 n 个
正数的数组长度 - n
prevNode.next = targetNode.next
/** * @param {ListNode} head * @param {number} n * @return {ListNode} */ let removeNthFromEnd = function (head, n) { let node = head let nodes = [] do { nodes.push(node) node = node.next } while (node) const l = nodes.length const index = l - n const targetNode = nodes[index] const prevNode = nodes[index - 1] if (prevNode) { prevNode.next = targetNode.next } const tempNext = targetNode.next targetNode.next = null if (targetNode === head) { return tempNext } return head }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
数组法
由于不知道链表有几个节点,所以先建立一个数组,用来记录节点对应的下标顺序。
求
倒数第 n 个
,可以转化成求正数的数组长度 - n
个,而通过数组又可以很容易的拿到待删除节点的前一个节点,那么就把前一个节点prevNode.next = targetNode.next
这样更换指向即可。The text was updated successfully, but these errors were encountered: