双指针法
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {number}
*/
var kthToLast = function(head, k) {
if(head === null) return null;
let first = head, second = head;
let node = head;
while(k > 0){
first = first.next;
k--;
}
console.log(first);
while(first){
second = second.next;
first = first.next;
}
return second.val;
};
堆栈法
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {number}
*/
var kthToLast = function(head, k) {
if(head === null) return null;
let arr = [];
let node = head;
while(node && (node.val || node.val === 0)){
arr.push(node.val);
node = node.next;
}
return arr[arr.length - k];
};
网友评论