题目描述
输入一个链表,输出该链表中倒数第k个结点。
提示:不要改变原链表的顺序
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if(pListHead==NULL) return NULL;
if(pListHead->next==NULL&&k==1)
{
return pListHead;
}
else if(pListHead->next==NULL&&k!=1)
{
return NULL;
}
ListNode* node=pListHead;
int count=0;
while(node)
{
node=node->next;
count++;
}
if(k>count)
{
return NULL;
}
int index=count-k+1;
count=1;
node=pListHead;
while(count<index)
{
node=node->next;
count++;
}
return node;
}
};