#include <vector>
#include <iostream>
#include <string>
#include <c++/algorithm>
#include <c++/map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int k) : val(k), next(NULL) {
}
};
ListNode* FindKthFromTail(ListNode* pListHead,int k) {
if (pListHead == NULL || k == 0)//防止空的链表 和 k值 等于 0 的情况
{
return NULL;
}
ListNode *pAhead = pListHead;
ListNode *pBehind = NULL;
for (int i = 0; i < k - 1; i++) {
if (pAhead->next != NULL) {
pAhead = pAhead->next;
} else {
return NULL;
}
}
pBehind = pListHead;
while (pAhead->next != NULL) {
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}
int main(){
ListNode * head = new ListNode(0);
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);
head->next=p1;
p1->next=p2;
p2->next=p3;
p3->next=p4;
p4->next=p5;
p5->next=NULL;
ListNode *pNode = FindKthFromTail(head, 3);
cout<<pNode->val<<endl;
return 0;
}
