Cycle listII
来源:互联网 发布:access数据库的优点 编辑:程序博客网 时间:2024/06/06 12:45
假设刚进环的时候慢指针走了m步,环的大小为n,快慢指针在距离环起点x步的时候相遇。慢指针是一定走不完一圈就会和快指针相遇的(因为最惨的情况下就是慢指针进圈的时候快指针在它前面一个,快指针速度时慢的两倍,这种悲剧情况下慢指针也不可能走完一圈就会被追到)。这是慢指针走了m+x步,快指针走了2(m+x)步,快指针在圈内走了2(m+x)-m=m+2x步。由于相遇在x位置,所以 m+2x % n = x,推出m+2x = i * n + x,于是m+x = i*n。我们注意到慢指针已经走了x步了,再走m步时一定会回到圈的起点的(m+x = i*n),所以等它们相遇后,一个指针从head开始走,然后慢指针从相遇的位置出发,则一定会相遇到圈的起点。
struct ListNode *detectCycle(struct ListNode *head) {struct ListNode *pCurrentSlow=head;struct ListNode *pCurrentFast=head;if (head==NULL){return NULL;}if (head->next!=NULL){pCurrentSlow=pCurrentSlow->next;//慢节点..}elsereturn NULL;if (pCurrentSlow->next!=NULL){pCurrentFast=pCurrentFast->next->next;//块节点..}elsereturn NULL;//环是n,确定相遇点m+x步,在圈内满指针已经走x步while(pCurrentFast->next!=NULL&&pCurrentFast->next->next!=NULL){if (pCurrentFast==pCurrentSlow ){ struct ListNode *pCurrentX=pCurrentSlow; pCurrentSlow=head; while(pCurrentSlow!=pCurrentX) { pCurrentSlow=pCurrentSlow->next;//pCurrentX=pCurrentX->next; } return pCurrentX;}else{pCurrentSlow=pCurrentSlow->next;//慢节点..pCurrentFast=pCurrentFast->next->next;//块节点..}}return NULL;}
0 0
- Cycle listII
- Reverse Linked ListII
- 2.2.2Reverse Linked ListII
- Remove Duplicates from Sorted ListII
- Remove Duplicates from Sorted ListII 有序链表去重II D3F3
- LeetCode92之Reverse Linked ListII的 Java题解
- LeetCode---Remove Duplicates from Sorted ListII解题分析
- smarty cycle
- nginx cycle
- retain cycle
- Retain Cycle
- CSU_1660_K-Cycle
- Find Cycle
- Hamiltonian Cycle
- cycle GAN
- Networkx-cycle
- cpu cycle 。。和 cycle有啥区别?
- leetcode Linked List Cycle & Linked List Cycle ||
- 开博 20150619
- EXTJS4 之 toolbar
- 怎样在Xcode 6中使用矢量图形
- 锁ReentrantLock简述
- 格式化字符串的使用
- Cycle listII
- IOS之地图和定位应用开发
- 安卓4.4后实现透明状态栏
- Eclipse快捷方式
- DEDE 取消勾选 下载远程图片和资源 图片水印等 附加选项
- java.lang.UnstatisfiedLinkError conldn't find xx.so 问题
- STUN/TURN/ICE协议在P2P SIP中的应用(一)
- perl中自己编译安装module
- FTP -- 使用Apache FtpServer搭建FTP服务器