#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
};
ListNode* AddToTail(ListNode *pHead,int value)
{
ListNode *pNew = new ListNode;
pNew->value = value;
pNew->next = NULL;
if (pHead == NULL)
{
pHead = pNew;
}
else
{
ListNode *pNode = pHead;
while(pNode->next != NULL)
{
pNode = pNode->next;
}
pNode->next = pNew;
}
return pHead;
}
ListNode *FindKthToTail(ListNode *pHead,int k)
{
if(pHead==NULL || k<=0)
return NULL;
ListNode *pFirst=pHead;
ListNode *pSecond=pHead;
for (int i=0 ; i<k ; ++i)
{
if (pFirst->next ==NULL)
return NULL;
pFirst = pFirst->next;
}
while(pFirst->next != NULL)
{
pFirst = pFirst->next;
pSecond = pSecond ->next;
}
return pSecond;
}
void main()
{
ListNode *phead=NULL;
ListNode *temp;
for (int i=0 ; i<10 ; ++i)
{
phead = AddToTail(phead,i+1);
}
temp = phead;
while(temp->next !=NULL)
{
cout<<temp->value<<endl;
temp = temp->next;
}
cout<<FindKthToTail(phead,2)->value<<endl;
}