题解 | #输出单向链表中倒数第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);
}
}