查找链表中倒数第k个结点 C++实现

来源:互联网 发布:有手机设计软件 编辑:程序博客网 时间:2024/05/29 07:17

输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};

如果我们在遍历时维持两个指针,第一个指针从链表的头指针开始遍历,在第k-1步之前,第二个指针保持不动;在第
k-1步开始,第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,当第一个(走在前面的)指
针到达链表的尾结点时,第二个指针(走在后面的)指针正好是倒数第k个结点。
这种思路只需要遍历链表一次。对于很长的链表,只需要把每个结点从硬盘导入到内存一次。

 

//============================================================================// Name        : FindLaskKInList.cpp// Author      : Lee// Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include <iostream>using namespace std;struct ListNode{int m_nKey;ListNode * m_pNext;};class LeeCom{private:ListNode * list;public:LeeCom():list(NULL){}LeeCom(ListNode * li):list(li){}void createList(int datas[],int len);bool getLastK(int k,int &res);};void LeeCom::createList(int datas[],int len){ListNode * p=new ListNode();p->m_nKey=datas[0];p->m_pNext=NULL;list=p;for(int i=1;i<len;i++){ListNode * next=new ListNode();next->m_nKey=datas[i];next->m_pNext=NULL;p->m_pNext=next;p=next;}}bool LeeCom::getLastK(int k,int &res){ListNode * pre = list;ListNode * p=list;if(NULL==p){return false;}for(int i=1;i<=k-1;i++){//p is k node ahead of pre;p=p->m_pNext;if(NULL==p){//there're less than k node;return false;}}while(NULL!=p->m_pNext){pre=pre->m_pNext;p=p->m_pNext;}res=pre->m_nKey;return true;}int main() {cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!int a[5]={4,6,3,2,7};LeeCom lee;lee.createList(a,5);int res=0;if(lee.getLastK(2,res)){cout<<res<<endl;}else{cout<<"false"<<endl;}return 0;}


 

0 0