题目描述
输入一个链表,输出该链表中倒数第k个结点。
#include<iostream>
using namespace std;
#include<cassert>
struct ListNode
{
int Val;
struct ListNode *next;
ListNode(int x):Val(x),next(NULL) { }
};
ListNode* FindKthToTail(ListNode *pListHead,unsigned int k)
{
assert(pListHead);
ListNode *pCur = pListHead;
while (--k)
{
if (pCur->next == NULL)
return NULL;
pCur = pCur->next;
}
ListNode *pPre = pListHead;
while (pCur->next)
{
pPre = pPre->next;
pCur = pCur->next;
}
return pPre;
}
void test()
{
ListNode *p1 = new ListNode(1);
ListNode *p2 = new ListNode(2);
ListNode *p3 = new ListNode(3);
ListNode *p4 = new ListNode(4);
ListNode *p5 = new ListNode(5);
p1->next = p2;
p2->next = p3;
p3->next = p4;
p4->next = p5;
ListNode *pK = FindKthToTail(p1,3);
cout << pK->Val <<endl;
delete p1;
delete p2;
delete p3;
delete p4;
delete p5;
}
int main()
{
test();
cout << "hello..." <<endl;
return 0;
}