题目: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?
源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)
/**
* 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(fast==slow) {
return true;
}
}
return false;
}
}
本文介绍了一种高效检测链表中是否存在环的方法。通过使用快慢指针技术,可以在O(n)的时间复杂度和O(1)的空间复杂度下完成检测。此方法避免了额外的空间开销。
309

被折叠的 条评论
为什么被折叠?



