142. Linked List Cycle II(链表)

匿名 (未验证) 提交于 2019-12-03 00:19:01

https://leetcode.com/problems/linked-list-cycle-ii/description/

题目:如果链表有环,返回环的入口,负责返回NULL.

思路:快慢指针,考虑下面的链表环,其中4->2表示4的下一元素为2。

1->2->3->4->2ft           st     flag 1            1      0 3            2      0 2            3      0 4            4      1  当flag为1时,ft与st指向同一元素:4  其中 ft 遍历的路径为:1->2->3->4->2->3->4,路径长度为6     st 遍历的路径为: 1->2->3->4         路径长度为3     ft的路径长度刚好为st的两倍,st回到head,继续  ft           st     flag 4            1      1 2            2      1  其中 ft 遍历的路径为: 4->2,      路径长度为1     st 遍历的路径为: 1->2        路径长度为1  路径长度相等,再次相遇即为入口地址。  
class Solution { public:     ListNode *detectCycle(ListNode *head) {              ListNode *ft = head, *st = head;              bool flag = 0;              while(ft&&ft->next){                   st = st->next;                   ft = (flag==1?ft->next:ft->next->next);                    if(st==ft&&!flag)                     st = head, flag = 1;                    if(st==ft && flag)                      return ft;             }         return NULL;     } };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!