提交网址: http://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167
//求链表的倒数第K个节点
/*
功能思路:用两个指针第一个走到第K-1个节点 第二个指向第K个节点
这时候二者同时出发 当第一个节点走到尾节点的时候 第二个节点即是倒数第K个节点
边界测试:k==0? 空指针? 返回nullptr
错误测试: 输入错误返回NULL
k输出为负数?
*/
#include<iostream>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x):
val(x),next(NULL){}
};
class Solution
{
public:
ListNode* FindKthToTail(ListNode *pListHead,unsigned int k)//功能 和错误测试K
{
if(pListHead==NULL||k==0)//边界
return nullptr;
ListNode *pAhead=pListHead;
ListNode *pBehind=nullptr;
for(unsigned int i=0;i<k-1;++i) //注意这里是k-1
{
if(pAhead->next!=nullptr)
{
pAhead=pAhead->next;
}
else
{
return nullptr;
}
}
pBehind=pListHead;
while(pAhead->next!=nullptr)
{
pAhead=pAhead->next;
pBehind=pBehind->next;
}
return pBehind;
}
};
int main()
{
ListNode *p_head,*kthNode;
Solution sol;
p_head=new ListNode(1);
p_head->next=new ListNode(2);
p_head->next->next=new ListNode(3);
p_head->next->next->next=new ListNode(4);
kthNode=sol.FindKthToTail(p_head,2);
// p_head=NULL;//空节点的情形,上面4个结点都注释掉
if(kthNode!=NULL)
cout<<kthNode->val<<endl;
else cout<<"The Node does not exist"<<endl;
return 0;
}