题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

构建链表,翻转链表,读取 k 值

class Node {
  constructor(v, next) {
    this.v = v;
    this.next = next;
  }
}

const reverseLinkedList = head => {
  let prev = null;
  let cur = head;
  while(cur) {
    const next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
  }
  return prev;
}

const createLinkedList = (nodeValues) => {
  // 构造链表
  const head = new Node(nodeValues[0], null)
  let cur = head;
  for(let i=1;i<nodeValues.length;i++) {
    const v = nodeValues[i];
    const node = new Node(v, null);
    cur.next = node;
    cur = node;
  }
  return head;
}

while(len = ~~readline()) {
  const nodeValues = readline().split(' ');
  let head = createLinkedList(nodeValues);
  // 翻转链表
  head = reverseLinkedList(head);
  let k = ~~readline();
  let result = head;
  if(k === 0) {
    console.log(0)
  } else {
    while(k) {
      result = result.next;
      k--
    }
    console.log(result.v);
  }
}
全部评论
没评论?
点赞 回复 分享
发布于 2024-09-10 15:58 北京

相关推荐

数开小菜鸡:你是我今早见过的最美的牛客女孩......
点赞 评论 收藏
分享
评论
16
3
分享

创作者周榜

更多
牛客网
牛客企业服务