您的位置:首页 > 其它

leetCode Linked List Cycle 解题分享

2014-08-03 15:48 253 查看
原题:https://oj.leetcode.com/problems/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?
查看一个单向链表是否构成环,要求不使用额外空间。

思路:创建两个指针,一快一慢,如果两个指针在某一时刻能重合,说明有环(如果有环,必存在一个最小公倍数,让两者迟早可以重合;如果无环,链表结尾必为null)

AC代码:

public class LinkedListCycle {

public boolean hasCycle(ListNode head) {

if(head == null) return false;

ListNode slow = head;
ListNode fast = head;

while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;

if(fast == slow) {
return true;
}

}
return false;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: