码迷,mamicode.com
首页 > 其他好文 > 详细

141. Linked List Cycle

时间:2016-09-12 06:15:35      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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

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

Solution1:

思路:有cycle:1.循环退不出来2.有个节点被指两次。分析清楚了就很简单,用hashset记录每个节点,如果碰到重复节点就是cycle,没有节点就会最终退出循环。

/**
 * 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) {
        Set<ListNode> res=new HashSet<ListNode>();
        if(head==null)
        {
            return false;
        }
        ListNode slow=head;
        while(slow!=null)
        {
            if(!res.contains(slow))
            {
                res.add(slow);
            }
            else
            {
                return true;
            }
            slow=slow.next;
        }
        return false;

        
    }
}

Solution2: 

dicussion中O(1)解法:快慢指针。如果有cycle,那么快慢指针肯定会相遇,如果没有cycle最终快慢指针不同。

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null && fast != slow && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        if(fast == slow) return true;
        return false;
    }
}

 

141. Linked List Cycle

标签:

原文地址:http://www.cnblogs.com/Machelsky/p/5863421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!