输出链表中倒数第k个结点

题目:输入一个单向链表,输出该链表中倒数第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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值