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; } }

浙公网安备 33010602011771号