您的位置:首页 > 其它

(leetcode)Linked List Cycle

2014-08-19 21:54 260 查看
题目描述:

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) {
if(head==null||head.next==null)
return false;
ListNode next2=head;
while(head!=null&&next2!=null&&next2.next!=null){
head=head.next;
next2=next2.next.next;
if(head==next2){
return true;
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: