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

输入一个单向链表,输出该链表中倒数第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;
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值