Linked List Cycle

有点取巧,p1 算不算多余的空间?
/**
* Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode p = head; ListNode p1 = head; while(p!=null&&p1!=null){ try{ p=p.next; p1 = p1.next.next; }catch(Exception e){ return false; } if(p==p1){ return true; } } return false; } }

 

posted @ 2014-06-10 23:34  SouHo  阅读(84)  评论(0)    收藏  举报