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

Linked List Cycle

时间:2014-11-20 21:46:01      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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?

这道题要用双指针,但我想试一下投机取巧的办法行不行,果然A了

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public boolean hasCycle(ListNode head) {
14         if(null == head)
15             return false;
16         ListNode point = head;
17         while(null != point){
18             if(point.val != Integer.MIN_VALUE)
19                 point.val = Integer.MIN_VALUE;
20             else
21                 return true;
22                 point = point.next;
23         }        
24         return false;
25     }
26 }

 双指针,一个走一步一个走两步,有环两个一定会相遇

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public boolean hasCycle(ListNode head) {
14         if(null == head)
15             return false;
16         ListNode slow = head;
17         ListNode fast = head;
18         while(fast != null && fast.next != null){
19             slow = slow.next;
20             fast = fast.next.next;
21             if(slow == fast)
22                 return true;
23         }
24         return false;
25     }
26 }

 

Linked List Cycle

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/luckygxf/p/4111376.html

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