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

[LeetCode]: 141: Linked List Cycle

时间:2015-09-17 11:25:22      阅读:132      评论: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来判断是否重复

 

代码:

    public boolean hasCycle(ListNode head) {
        HashSet hashFlag = new HashSet();
        while(head!= null){
            if(!hashFlag.add(head)){
                return true;
            }
            head = head.next;
        }
        return false;
    }

 

思路二:采用快指针和慢指针

两个指针,移动的速度差一,所以快指针必定会“追上”慢指针。有点类似小学时候的追击问题

 

代码:

    public boolean hasCycle(ListNode head) {
        ListNode Fast = head;
        ListNode Slow = head;
        while(Slow!= null){
            if(Slow.next!= null && Fast.next!= null && Fast.next.next!= null){
                Slow = Slow.next;
                Fast = Fast.next.next;
                if(Slow == Fast){
                    return true;
                }
            }
            else{
                return false;
            }

        }
        return false;
    }

 

222

[LeetCode]: 141: Linked List Cycle

标签:

原文地址:http://www.cnblogs.com/savageclc26/p/4815618.html

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