Linked List Cycle(Easy)

2019-08-09  本文已影响0人  海生2018

Given a linked list, determine if it has a cycle in it.

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.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
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: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

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

Follow up:

Can you solve it using O(1) (i.e. constant) memory?


Solution

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode first=head;
        ListNode second=head;
        boolean flag=true;
        while(first!=null&&second!=null&&second.next!=null){
            if(!flag&&first.val==second.val){
                return true;
            }
            first=first.next;
            second=second.next.next;
            flag=false;
        }
        return false;
    }
}

时间:O(n)
空间:O(1)

我蠢了,写得太复杂了,我执着于两个指针的开始位置,其实只要是一快一慢肯定能相遇。每轮第一个走一步,第二个走两步,只要没遇见null就可能存在环,两个指针指向的值相等就确认有环了。哈希表也可以做,就是空间上会变为O(n)

上一篇 下一篇

猜你喜欢

热点阅读