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

Linked List Cycle——LeetCode

时间:2015-04-22 11:29:06      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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

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

题目大意:给定一个链表,判断是否有环?

解题思路:

解法一:快慢指针,如果有环,那么快慢指针总会相遇,有环;否则快的遍历完整个链表,无环。

解法二:HashSet保存节点,如果下一个节点在set中出现过,那么有环,否则直到遍历完整个链表,无环。

Talk is cheap>>

解法一:

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

解法二:

    public boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

 

Linked List Cycle——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4446675.html

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