题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
思路很简单
1.
遍历链表的同时 k–
遍历完链表如果k0说明找的就是第一个结点
如果小于0 进行第二步
2.遍历链表的同时k++
当k0时找到该结点
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k == 0) {
return null;
}
ListNode temp = head;
ListNode res = null;
while(temp != null) {
k--;
temp = temp.next;
}
if(k == 0){
res = head;
}else if(k < 0) {
temp = head;
while(++k != 0) {
temp = temp.next;
}
res = temp.next;
}
return res;
}
}