LeetCode(141): Linked List Cycle

Linked List Cycle: Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

题意:判断一个链表中是否存在环。

思路:(参考别人的做法)采用“快慢指针”检查链表是否含有环。即让一个指针一次走一步,另一个指针一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。

代码:

public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow==fast)
            return true;
        }
        return false;
    }
posted @ 2016-01-15 21:14  Lewisr  阅读(127)  评论(0编辑  收藏  举报