题目描述
输入一个链表,输出该链表中倒数第k个结点。
遍历1次,当走了k步时,标记头结点,接下来继续向后遍历,同时标记也往后走,等遍历完链表的时候,标记刚好停留在倒数第k个位置
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null || k<=0) {
return null;
}
int count=0;
ListNode p = head;
ListNode target = null;
while(p!=null) {
count++;
if(target!=null) {
target = target.next;
}
if(count==k) {
target = head;
}
p=p.next;
}
return target;
}
}