LeetCode-142.Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Follow up:
Can you solve it without using extra space?

空间复杂度O(n)

public ListNode detectCycle(ListNode head) {//链表 my
        Set<ListNode> nodeSet = new HashSet<ListNode>();
        while(null!=head){
            if(nodeSet.contains(head)){
                return head;
            }
            else{
                nodeSet.add(head);
                head=head.next;
            }
        }
        return null;
    }

空间复杂度O(1)

a=从头结点-》环入口的距离,b=从环入口-》快慢两个结点的相遇处的距离,c=环的长度-b。

快结点走的长度=a+b+c+b,慢结点走的长度=a+b;所以a+b+c+b=2(a+b),可得a=c。

故慢结点从相遇的结点继续走,一步一个结点,另一结点从头结点开始走,一步一个结点,两个结点相遇处就是环入口。

 1 public ListNode EntryNodeOfLoop(ListNode pHead){//链表 my
 2         if(null==pHead||null==pHead.next){
 3             return null;
 4         }
 5         ListNode one = pHead.next;
 6         ListNode two = pHead.next.next;
 7         while(null!=one&&null!=two&&null!=two.next&&one!=two){
 8             one = one.next;
 9             two = two.next.next;
10         }
11         if(null==two||null==two.next||null==one){
12             return null;
13         }
14         two = pHead;
15         while(one !=two){
16             one = one.next;
17             two = two.next;
18         }
19         return one ;
20     }

 

简洁代码

public ListNode detectCycle(ListNode head) {//mytip
        ListNode oneStep =head;
        ListNode twoStep = head;
        while(null!=oneStep&&null!=twoStep&&null!=twoStep.next){
            oneStep=oneStep.next;
            twoStep= twoStep.next.next;
            if (oneStep==twoStep){
                twoStep=head;
                while(twoStep!=oneStep){
                    twoStep=twoStep.next;
                    oneStep=oneStep.next;
                }
                return oneStep;
            }
        }
        return null;
    }

  

 相关题

判断链表是否有环 LeetCode141   https://www.cnblogs.com/zhacai/p/10560803.html

posted @ 2019-03-19 20:37  月半榨菜  阅读(145)  评论(0编辑  收藏  举报