这道题很简单,利用双指针。 主要是以下几个注意点
1. 判断链表是否为空
2. 判断k是否为0,若为0无意义
3.判断k是否超出了链表长度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
//双指针
if(!head || k==0) return NULL;
ListNode *slow = head;
ListNode *fast = head;
for(int i=0;i<k;++i)
{
if(fast==NULL) //不足k个
{
return head;
}
else
{
fast=fast->next;
}
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};