【leetcode刷题笔记】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?


 

题解:参见http://www.cnblogs.com/sunshineatnoon/p/3825032.html

代码如下:

 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         ListNode p1 = head;

15         ListNode p2 = head;

16         

17         while(p2 != null){

18             p1 = p1.next;

19             p2 = p2.next;

20             if(p2 != null)

21                 p2 = p2.next;

22             else 

23                 return false;

24             if(p1 == p2)

25                 return true;

26         }

27         return false;

28     }

29 }

 

你可能感兴趣的:(LeetCode)