Linked List Cycle——LeetCode

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

 

posted @ 2015-04-22 10:33  丶Blank  阅读(168)  评论(0编辑  收藏  举报