首页 > 其他 > 详细

Linked List Cycle——LeetCode

时间:2015-04-22 11:27:08      阅读:202      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!