求链表中环的入口
来源:互联网 发布:企业数据库的建立 编辑:程序博客网 时间:2024/04/27 20:25
链表中没环就返回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 headwhile(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;}
0 0
- 求链表中环的入口
- 求链表中环的入口点
- 剑指 offer 56:求链表中环的入口节点
- Google的秘密入口
- Google的秘密入口
- Google的秘密入口
- Google的秘密入口
- Google的秘密入口
- google的秘密入口
- Google的秘密入口
- google的秘密入口
- google的秘密入口
- Google的秘密入口
- google的秘密入口
- MFC的入口
- 互联网的入口
- OEP入口的特征
- 驱动程序的入口函数
- 时间格式相加减方法
- UIAlertView的基本使用和对话框中按钮的事件处理方法
- 二八杠怎么控牌▅『【在线演示QQ:194714506】
- Azure SQL 数据库与新的数据库吞吐量单位
- 二八杠怎样控牌∏▲【在线演示QQ:194714506】
- 求链表中环的入口
- 二八杠控牌绝技╱▃【在线演示QQ:194714506】
- MVC大型商贸系统(库存管理)技术解释(三) 主界面设计
- 二八杠能控牌吗●※【在线演示QQ:194714506】
- 如何实现企业管理系统的操作日志功能
- 第三章四十三题
- android自动登录界面
- 如何搭建Android开发环境?java环境搭建全集教程
- Android中的volley_9_ResponseDelivery和ExecutorDelivery