Implement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.
Note: This problem is slightly different from the original one in the book.
Example:
Input: 1->2->3->4->5 和 k = 2 Output: 4
Note:
k is always valid.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
p = q = head
for _ in range(k):
q = q.next
while q:
p, q = p.next, q.next
return p.val
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int kthToLast(ListNode head, int k) {
ListNode p = head, q = head;
while (k-- > 0) {
q = q.next;
}
while (q != null) {
q = q.next;
p = p.next;
}
return p.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) {
let fast = head, slow = head;
for (let i = 0; i < k; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow.val;
};