LeetCode | Linked List Cycle
2014-12-04 20:45
316 查看
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
tags提示:two pointers
采用“快慢双指针”的方法来判断:
每次slow_pointer前进一格,而fast_pointer前进两格,如若list存在cycle的话,则快指针一定会与慢指针重合。(因为当list存在cycle时,向后遍历是一个无限循环的过程,在此循环中两指针一定会重合)
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow_pointer = head;
ListNode fast_pointer = head;
while(fast_pointer!=null && fast_pointer.next!=null){ //向后遍历中出现null,则一定无cycle
slow_pointer = slow_pointer.next;
fast_pointer = fast_pointer.next.next;
if(slow_pointer == fast_pointer){ //如果快指针与慢指针重合了,则一定有cycle
return true;
}
}
return false;
}
}
Follow up: Can you solve it without using extra space?
tags提示:two pointers
采用“快慢双指针”的方法来判断:
每次slow_pointer前进一格,而fast_pointer前进两格,如若list存在cycle的话,则快指针一定会与慢指针重合。(因为当list存在cycle时,向后遍历是一个无限循环的过程,在此循环中两指针一定会重合)
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow_pointer = head;
ListNode fast_pointer = head;
while(fast_pointer!=null && fast_pointer.next!=null){ //向后遍历中出现null,则一定无cycle
slow_pointer = slow_pointer.next;
fast_pointer = fast_pointer.next.next;
if(slow_pointer == fast_pointer){ //如果快指针与慢指针重合了,则一定有cycle
return true;
}
}
return false;
}
}
相关文章推荐
- LeetCode: Linked List Cycle 解题报告
- leetcode 137: Linked List Cycle
- leetcode 142 —— Linked List Cycle II
- [leetcode]Linked List Cycle
- LeetCode--linked-list-cycle
- LeetCode: Linked List Cycle
- LeetCode | Linked List Cycle(判断链表是否有环)
- [LeetCode 第10题] -- Linked List Cycle
- [LeetCode 第11题] -- Linked List Cycle II
- Leetcode | Linked List Cycle I && II
- leetcode--Linked List Cycle
- LeetCode - linked-list-cycle-ii
- LeetCode: Linked List Cycle
- 【LeetCode】Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode之Linked List Cycle II
- [LeetCode]Linked List Cycle
- leetcode--LinkedListCycleII
- LeetCode:141. Linked List Cycle
- [LeetCode]Linked List Cycle