Linked List Cycle
https://leetcode.com/problems/linked-list-cycle/description/
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Thoughts
有环意味着什么?想想我们跑圈时,跑得慢的能被跑得快的追上。利用这个思想。
Code
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Analysis
Errors:
让跑得慢起点在前。导致即使无环也追上了
忘了写node != null作为循环条件。
时间复杂度O(n)
Last updated
Was this helpful?