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;
}
}
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;
}
}
相关文章推荐
- LeetCode — Linked List Cycle II 解题报告
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- LeetCode: Linked List Cycle 解题报告
- LeetCode — Linked List Cycle 解题报告
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- LeetCode 解题报告 LinkedListCycleII
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
- [LeetCode] Linked List Cycle
- LeetCode Linked List Cycle II 和I 通用算法和优化算法
- Leetcode: Linked List Cycle
- [leetcode]Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- Leetcode Linked List Cycle
- leetcode 之 Linked List Cycle
- [LeetCode] Reverse Linked List II 解题报告