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

[leetcode]Linked List Cycle

时间:2014-07-19 18:38:30      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

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?

算法

思路1:

快慢指针,当两个指针相遇,则表示有环,否则则无环,可能需要多遍遍历,空间复杂度O(1),时间复杂度O(n)

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if(head == null) return false;
 4         ListNode fast = head;
 5         ListNode slow = head;
 6         while(true){
 7             if(fast.next == null || fast.next.next == null) return false;
 8             fast = fast.next.next;
 9             slow = slow.next;
10             if(fast == slow) return true;
11         }
12     }
13 }

 

思路2:

hash表,当某个节点有两个前驱,则该节点是环的起点,而且只需一次遍历,空间复杂度O(n),时间复杂度O(n)

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if(head == null) return false;
 4         ListNode tem = new ListNode(0);
 5         tem.next = head;
 6         Map<ListNode,ListNode> hash = new HashMap<ListNode,ListNode>();
 7         while(true){
 8             if(tem.next == null) return false;
 9             if(hash.get(tem.next) != null) return true;
10             hash.put(tem.next,tem);
11             tem = tem.next;
12         }
13     }
14 }

思路2同样是Linked List Cycle II的解法

 

ListNode的结构如下:

bubuko.com,布布扣
1 public class ListNode {
2     int val;
3     ListNode next;
4     ListNode(int x){
5         val = x;
6         next = null;
7     }
8 }
View Code

[leetcode]Linked List Cycle,布布扣,bubuko.com

[leetcode]Linked List Cycle

标签:style   blog   http   color   os   art   

原文地址:http://www.cnblogs.com/huntfor/p/3854969.html

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