Skip to content
New issue

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个节点-19 #46

Open
sl1673495 opened this issue May 31, 2020 · 0 comments
Open

删除链表的倒数第N个节点-19 #46

sl1673495 opened this issue May 31, 2020 · 0 comments
Labels

Comments

@sl1673495
Copy link
Owner

给定一个链表,删除链表的倒数第  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 这样更换指向即可。

/**
 * @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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant