More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/linked-list-cycle/java
Given a linked list, determine if it has a cycle in it.post
Follow up:
Can you solve it without using extra space?ui
Use two pointers at different speed: the slow pointer moves one step at a time while the faster moves two steps at a time. spa
1) if the fast pointer meets the slow one, there is a cycle in the linked list;code
2) if the fast pointer reaches the end(null), there is no cycle in the list.htm
public boolean hasCycle(ListNode head) { if(head==null) return false; int fast=head; int slow=head; while(fast.next!=null && fast.next.next!=null){ slow=slow.next; fast=fast.next.next; if(fast==slow) return true; } return false; }
Time complexity : O(n)
blog
Space complexity : O(1)
ip
1. Have a better understanding of the use of two pointers.leetcode
More:【目錄】LeetCode Java實現