博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求链表中环的入口
阅读量:7266 次
发布时间:2019-06-29

本文共 1749 字,大约阅读时间需要 5 分钟。

链表中没环就返回NULL

有就返回环的入口

三种基本思路:

1、快慢指针找到环内的一个node,然后从链表头開始。对于每个node,看它在不在环中

2、用map存一下訪问过的节点地址,看当前node的地址是否在map中

3、事实上。经过计算,对于1中,快慢指针相遇的地方,再開始以慢指针開始走。

还有一方面,在链表的头部也用一个慢指针開始走,二者相遇的地方便是环的入口

(代码并未进行执行验证)

typedef struct node{	int data;	struct node * next;}listNode;

//find the first node in the cycle//1.step into the circle first and then for every node, take a loop to make sure//2.store the previous node and compare with the cunrrent node (what structure to store?)//3.after computation,while using slow and fast pointer,// we can get that a slow pointer at the begining and another one // at the encounter position will meet at the entrance of the cycle listNode *findFirstNodeInCycle1(listNode *pHead){	listNode *pFast=pHead;	listNode *pSlow=pHead;	while(pFast!=NULL&&pFast->next!=NULL)	{		pFast=pFast->next->next;		pSlow=pSlow->next;		if(pSlow==pFast)			break;	}	if(pFast==NULL||pFast->next==NULL)		return NULL;	//now the nodes are in the loop	//begin with the head	while(pHead)	{				pSlow=pSlow->next;		while(pSlow)		{			if(pSlow==pHead)				return pHead;			if(pSlow==pFast)				break;					pSlow=pSlow->next;		}		pHead=pHead->next;	}}//store in a map?

good or not? listNode *findFirstNodeInCycle2(listNode *pHead) { if(pHead==NULL) return; listNode *temp=pHead-next; map<int,char> storeMap; map[int(pHead)]=' '; while(teamp!=NULL&&storeMap.find(temp)==storeMap.end()) { storeMap[int(temp)]=' '; temp=temp->next; } return temp; } listNode *findFirstNodeInCycle3(listNode *pHead) { listNode *pFast=pHead; listNode *pSlow=pHead; while(pFast!=NULL&&pFast->next!=NULL) { pFast=pFast->next->next; pSlow=pSlow->next; if(pFast==pSlow) { listNode *pSlow2=pHead; while(pSlow2!=pSlow) { pSLow=pSlow->next; pSlow2=pSlow2->next; } return pSlow; } } return NULL; }

转载地址:http://gdfcm.baihongyu.com/

你可能感兴趣的文章
java 查看线程死锁
查看>>
IOS之表视图添加索引
查看>>
IO流-文件管理
查看>>
PHP如何判断远程图片文件是否存在
查看>>
【Android】11.0 第11章 活动和片段--本章示例主界面
查看>>
【答】如何获取一个【备份路径】的信息?
查看>>
课堂练习 选择团队类型
查看>>
Git 入门和常用命令详解
查看>>
linux 进阶命令___0001
查看>>
【 python 学习笔记 -- 数据结构与算法 】选择排序 Selection Sort
查看>>
数据结构与算法基础
查看>>
rsync
查看>>
第四十条:谨慎设计方法签名
查看>>
2018-2019-1 20165335 《信息安全系统设计基础》第7周学习总结
查看>>
PHP中数组遍历的几种方法
查看>>
解决Sublime Text 2中文显示乱码问题
查看>>
php页面输出时,js设置input框的选中值
查看>>
Linux 系统下 matplotlib 中文乱码解决办法
查看>>
Public Prize
查看>>
QuickSort
查看>>