首页 > 其他 > 详细

[LeetCode] Linked List Cycle

时间:2015-08-19 16:31:54      阅读:148      评论:0      收藏:0      [点我收藏+]

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

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

 

     关于cycle,第一个想法自然就是用hashmap来做。注意用hashmap.put()method的时候,value随便设置一个数就可以了。

     因为我们只是检测key是否有重复的,value在这里的意义不大。

     代码如下。~

/**
 * 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) {
        HashMap<ListNode,Integer> hash=new HashMap<ListNode,Integer>();
        if(head==null){
            return false;
        }
        while(head!=null){
            if(hash.containsKey(head)){
                return true;
            }
            hash.put(head,1);
            head=head.next;
        }
        return false;
    }
}

      但是再看一下follow up那里要求的是without extra space,那么这样的话hashmap就暂时不能用了。

      用two pointer来做就可以了。快慢指针。(fase/slow) (fast每次走两步,slow则是一步。)

      如果有cycle的话,快慢指针一定会相遇。

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

 

      

 

[LeetCode] Linked List Cycle

原文:http://www.cnblogs.com/orangeme404/p/4742333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!