题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include<iostream>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
ListNode(int k):m_nKey(k),m_pNext(NULL){}
};
int main()
{
int n;
while(cin>>n)
{
ListNode *pHead=NULL;
ListNode *pTempHead=NULL;
while(n--)
{
int d;
cin>>d;
ListNode *pNode=new ListNode(d);
if(pHead==NULL)
{
pHead=pNode;
pTempHead=pHead;
}
else
{
pTempHead->m_pNext=pNode;
pTempHead=pNode;
}
}
int k;
cin>>k;
pTempHead=pHead;
while(k--&&pTempHead)
{
pTempHead=pTempHead->m_pNext;
}
while(pHead&&pTempHead)
{
pHead=pHead->m_pNext;
pTempHead=pTempHead->m_pNext;
}
if(pHead)
{
cout<<pHead->m_nKey<<endl;
}
else
{
cout<<NULL<<endl;
}
}
return 0;
}