Skip to content

LeetCode题解:剑指 Offer 22. 链表中倒数第k个节点,使用栈,JavaScript,详细注释 #220

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

解题思路:

  1. 利用栈先进后出的特点,只要将所有节点都存入栈,再依次取出n-1个,栈顶元素即为倒数第k个节点。
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var getKthFromEnd = function(head, k) {
  let stack = [] // 使用栈存储链表的节点

  // 遍历链表,将所有节点都存入栈
  while (head) {
    stack.push(head)
    head = head.next
  }

  // 弹出k-1个节点
  while (--k > 0) {
    stack.pop()
  }

  // 栈顶即为倒数第k个元素
  return stack[stack.length - 1]
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions