[Leetcode]141. 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 /**
 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 }

 

posted @ 2017-11-01 12:50  SkyMelody  阅读(92)  评论(0编辑  收藏  举报