您的位置:首页 > 职场人生

面试9之输入一个链表,输出该链表中倒数第k个结点。

2017-04-21 16:55 369 查看


题目描述

输入一个链表,输出该链表中倒数第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐