当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度: Easy

内容描述

  1. 给定一个链表,确定其中是否有一个循环。
  2. 跟进:
  3. 你能在不占用额外空间的情况下解决它吗?

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

快慢指针

  1. java
  2. public class Solution {
  3. public boolean hasCycle(ListNode head) {
  4. if (head == null){
  5. return false;
  6. }
  7. ListNode fast = head;
  8. ListNode slow = head;
  9. while (fast != null && slow != null && fast.next != null){
  10. fast = fast.next.next;
  11. slow = slow.next;
  12. if (slow == fast){
  13. return true;
  14. }
  15. }
  16. return false;
  17. }
  18. }

该分类下的相关小册推荐: