输入一个链表,输出该链表中倒数第k个结点。
- 思路
定义两个指针:top和tail。
tail指针先走 k-1 步,到达第 k 个节点。
然后两指针同时齐步走,当tail指针到达末尾时,top指针在倒数第 k 个节点上。
public ListNode FindKthToTail(ListNode head,int k) {
ListNode tail = head;
ListNode top = head;
int count = 0;
while(tail != null){
tail = tail.next;
if(count >= k)
top = top.next;
count++;
}
if(count < k)
return null;
return top;
}