题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
//coder:LEE
//20120309
#include<iostream>
#include<cassert>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
void CreateListNode(ListNode *pHead)
{
for (int i=3;i<15;i++)
{
ListNode *pCur=new ListNode();
pCur->m_nKey=i;
pCur->m_pNext=NULL;
pHead->m_pNext=pCur;
pHead=pCur;
}
}
void DisplayListNode(ListNode *pHead)
{
while (pHead)
{
cout<<pHead->m_nKey<<" ";
pHead=pHead->m_pNext;
}
cout<<endl;
}
void BackOutputKNode(ListNode *pHead,int k)
{
assert(pHead!=NULL&&k>=0);
ListNode *pFirst=pHead;
ListNode *pSecond=pHead;
for(int i=0;i<k;i++)
{
pFirst=pFirst->m_pNext;
if(pFirst==NULL)
break;
}
if (i!=k)
{
cout<<"no enough datas or k is too big"<<endl;
return;
}
while (pFirst->m_pNext)
{
pFirst=pFirst->m_pNext;
pSecond=pSecond->m_pNext;
}
cout<<"the "<<k<<"th value to count from the end is:"<<pSecond->m_nKey<<endl;
}
int main()
{
ListNode *pHead=new ListNode();
pHead->m_nKey=0;
pHead->m_pNext=NULL;
CreateListNode(pHead);
DisplayListNode(pHead);
BackOutputKNode(pHead,3);
BackOutputKNode(pHead,0);
BackOutputKNode(pHead,22);
return 0;
}
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
//coder:LEE
//20120309
#include<iostream>
#include<cassert>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
void CreateListNode(ListNode *pHead)
{
for (int i=3;i<15;i++)
{
ListNode *pCur=new ListNode();
pCur->m_nKey=i;
pCur->m_pNext=NULL;
pHead->m_pNext=pCur;
pHead=pCur;
}
}
void DisplayListNode(ListNode *pHead)
{
while (pHead)
{
cout<<pHead->m_nKey<<" ";
pHead=pHead->m_pNext;
}
cout<<endl;
}
void BackOutputKNode(ListNode *pHead,int k)
{
assert(pHead!=NULL&&k>=0);
ListNode *pFirst=pHead;
ListNode *pSecond=pHead;
for(int i=0;i<k;i++)
{
pFirst=pFirst->m_pNext;
if(pFirst==NULL)
break;
}
if (i!=k)
{
cout<<"no enough datas or k is too big"<<endl;
return;
}
while (pFirst->m_pNext)
{
pFirst=pFirst->m_pNext;
pSecond=pSecond->m_pNext;
}
cout<<"the "<<k<<"th value to count from the end is:"<<pSecond->m_nKey<<endl;
}
int main()
{
ListNode *pHead=new ListNode();
pHead->m_nKey=0;
pHead->m_pNext=NULL;
CreateListNode(pHead);
DisplayListNode(pHead);
BackOutputKNode(pHead,3);
BackOutputKNode(pHead,0);
BackOutputKNode(pHead,22);
return 0;
}