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

Leetcode Linked List Cycle

时间:2015-11-13 06:17:45      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

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

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


解题思路:

If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the slow one if there exists a circle.

The problem can be demonstrated in the following diagram:

技术分享

复杂度O(n)的方法,使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。

为什么有环的情况下二者一定会相遇呢?因为fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。


Java code

/**
 * 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) {
        ListNode fast = head; //fast pointer moves two steps forward
        ListNode slow = head; //slow pointer moves one step forward
      
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
}

Reference:

1. http://www.programcreek.com/2012/12/leetcode-linked-list-cycle/

2. http://www.cnblogs.com/hiddenfox/p/3408931.html

3. http://yucoding.blogspot.com/2013/10/leetcode-question-linked-list-cycle.html

 

Leetcode Linked List Cycle

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4960786.html

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