首页 > 其他 > 详细

[Leetcode]141. Linked List Cycle

时间:2017-11-01 14:20:30      阅读:273      评论:0      收藏:0      [点我收藏+]

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

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

 

思路:快慢指针,设置一个走两步的快指针,和一个走一步的慢指针,如果有环,则它们一定会相遇。

 

 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 (head==null)
15             return false;
16         ListNode p1 = head,p2 = head.next;
17         while (p2!=null){
18             p2 = p2.next;
19             if (p2==null)
20                 return false;
21             p2 = p2.next;
22             p1 = p1.next;
23             if (p2==p1)
24                 return true;
25         }
26         return false;
27     }
28 }

 

[Leetcode]141. Linked List Cycle

原文:http://www.cnblogs.com/David-Lin/p/7765919.html

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