题目
返回 值:
返回 节点:
解题
解题一:迭代法
链表题经常会用双指针来做,这道题便是一个典型。
// javascript
var kthToLast = function(head, k) {
let fast = head, slow = head;
let stepAhead = 0;
while (fast !== null) {
fast = fast.next;
if (stepAhead !== k) {
stepAhead++;
}
else {
slow = slow.next;
}
}
return slow.val; // return slow; // 剑指 Offer 22. 链表中倒数第k个节点
};
// javascript
var kthToLast = function(head, k) {
let fast = head, slow = head;
let stepAhead = 0;
while (fast.next !== null) {
fast = fast.next;
if (stepAhead < k) {
stepAhead++;
}
if (stepAhead === k) { // 提前跑一步
slow = slow.next;
}
}
return slow.val; // return slow; // 剑指 Offer 22. 链表中倒数第k个节点
};
// or
var kthToLast = function(head, k) {
let fast = head, slow = head;
while (k > 0 && fast !== null) {
k--;
fast = fast.next;
}
while (fast !== null) {
slow = slow.next;
fast = fast.next;
}
return slow.val; // return slow; // 剑指 Offer 22. 链表中倒数第k个节点
};
解题二:递归
// javascript
var Idx = function(value) {
this.val = value;
};
var findKthToLast = function(head, k, idxToLast) { // idxToLast要传进来
if (head === null) return head;
let retNode = findKthToLast(head.next, k, idxToLast);
idxToLast.val++;
if (idxToLast.val === k) {
return head;
}
return retNode;
};
var kthToLast = function(head, k) {
let idxToLast = new Idx(0);
let nodeFound = findKthToLast(head, k, idxToLast);
return nodeFound.val;
};
// or
var Node = function(idx, node) {
this.idx = idx;
this.node = node;
};
var findKthToLast = function(head, k) {
if (head === null) {
let retNode = new Node(0, null);
return retNode;
}
let retNode = findKthToLast(head.next, k);
retNode.idx++;
if (retNode.idx === k) {
retNode.node = head;
}
return retNode;
};
var kthToLast = function(head, k) {
let nodeFound = findKthToLast(head, k);
return nodeFound.node.val;
};
可能是先入为主接受了第一种解法,递归反而变得不太直观,但还是依葫芦画瓢写了一下解法。
递归的方法效率要比迭代来得低。