程序员成长之旅——输出倒数第k个结点
作者:互联网
程序员成长之旅——输入一个链表,输出该链表中倒数第k个结点
题目简介
1->2->3->4->5->6
输出:4
提示: 可以运用快慢指针
牛客
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode* fast = pListHead;
ListNode* slow = pListHead;
ListNode* ctl = pListHead;
int count = 0;
if(pListHead == NULL)
return NULL;
while(ctl != NULL)
{
ctl = ctl->next;
count ++;
}
if(count < k)
return NULL;
while(k--)
{
fast = fast->next;
}
while(fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
标签:结点,ListNode,pListHead,int,fast,next,程序员,NULL,倒数第 来源: https://blog.csdn.net/wuweiwuju___/article/details/95775628