您的位置:首页 > 其它

CODE 138: Linked List Cycle

2013-11-24 16:07 218 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(null == head){
return false;
}
ListNode first = head;
ListNode second = head;
while(first.next != null && first.next.next !=null){
if(first.next.equals(second) || first.next.next.equals(second)){
return true;
}
first = first.next.next;
second = second.next;
}
if(first.next != null && first.next.equals(second)){
return true;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: