/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcgetKthFromEnd(head*ListNode,kint)*ListNode{slow,fast:=head,headfor;k>0;k--{fast=fast.Next}forfast!=nil{slow,fast=slow.Next,fast.Next}returnslow}
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } *//** * @param {ListNode} head * @param {number} k * @return {ListNode} */vargetKthFromEnd=function(head,k){letfast=head;while(k--){fast=fast.next;}letslow=head;while(fast){slow=slow.next;fast=fast.next;}returnslow;};
1 2 3 4 5 6 7 8 9101112131415161718192021
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */publicclassSolution{publicListNodeGetKthFromEnd(ListNodehead,intk){ListNodefast=head,slow=head;while(k-->0){fast=fast.next;}while(fast!=null){slow=slow.next;fast=fast.next;}returnslow;}}