142. Linked List Cycle II(链表)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/80426803

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;
    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/80426803
今日推荐