一遍通过
- 判空
- 定义快慢指针
- fast指针先跑k个结点 - n=0,则从输出头指针,n+1, 结点后移1
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
// write code here
// 判空
if(pHead == NULL)
{
return pHead;
}
int n = 0;
struct ListNode * fast = pHead;
struct ListNode * slow = pHead;
while( fast != NULL && n < k)
{
fast = fast->next;
n++;
}
if(fast == NULL && n == k)
{
return pHead;
}
if(fast == NULL && n < k)
{
return NULL;
}
while(fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}