LeetCode 141. Linked List Cycle

本文介绍两种检测链表中是否存在环的有效方法。一种是通过使用集合来存储已访问过的节点,另一种则是采用快慢指针的技术。这两种方法都能有效地解决链表环检测问题,并提供了计算环形链表长度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 1 /**
 2  * Definition for singly-linked list.
 3  */
 4 class ListNode {
 5     int val;
 6     ListNode next;
 7 
 8     ListNode(int x) {
 9         val = x;
10         next = null;
11     }
12 }

思路1:

  1. 遍历链表把所有的节点放入set中
    1. 若set中包含当前节点,则含有环
    2. 若set中没有,则把节点放入set
    3. 取下一个节点
  2. 若节点为null,则遍历结束,肯定没有环。

代码1:

 1   public boolean hasCycleBySet(ListNode head) {
 2         Set<ListNode> set = new HashSet<>();
 3         while(head != null){
 4             if(set.contains(head))
 5                 return true;
 6             else
 7                 set.add(head);
 8             head = head.next;
 9         }
10         return false;
11     }

思路2:

  1. 遍历链表,一次快(每次获取后面第二个),一次慢(每次获取后面第一个)
  2. 若快的节点为null或下一个为null,则不包含环
  3. 在若干次之后,若快的节点与慢的节点相同则包含环。(此时快的遍历比慢的遍历领先了一个链表的长度)

代码2:

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

扩展:计算环形链表的长度可参考思路二,快慢相差一个链表的长度,相减即可获得长度。

 1 public static boolean hasCycle(ListNode head) {
 2         if (head == null || head.next == null) {
 3             return false;
 4         }
 5         ListNode slow = head;
 6         ListNode fast = head.next;
 7         int f = 1;//上面两行赋值已前进了一次
 8         while (slow != fast) {
 9             if (fast == null || fast.next == null) {
10                 return false;
11             }
12             slow = slow.next;
13             fast = fast.next.next;
14             f++;
15         }
16         System.out.println("LinkedList.size:"+f);
17         return true;
18     }

 

转载于:https://www.cnblogs.com/angryorange/p/5908600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值