环形链表

leetCode–141(环形链表)

给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

如果链表中存在环 ,则返回 true 。 否则,返回 false 。

示例 1:

image-20220606185854338

1
2
3
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

image-20220606185909591

1
2
3
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

image-20220606185915956

1
2
3
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

解法一:set集合

使用set集合进行判断是否有环,因为如果有环存在,则一定会访问到重复的元素,由于set中不能存储重复元素,所以遇到重复元素就说明有环。

代码为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while (head!=null){
if (!set.add(head)){
return true;
}
head = head.next;
}
return false;
}
}

之前写的时候,是想到用值来判断set集合中是否有该节点,但是用例没有过去,因为节点的值也有可能相等,所以,set的类型要为ListNode才可以。

解法二:快慢指针

我们定义两个指针,一快一满。慢指针每次只移动一步,而快指针每次移动两步。如果有环 则快指针和慢指针一定会相遇,如果没有环,则快指针为空。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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;
ListNode fast = head;
while (fast!=null && slow!=null){
if (fast.next!=null) {
fast = fast.next.next;
}else return false;
if (slow.next!=null) {
slow = slow.next;
}else return false;
if (fast==slow) break;
}
if (fast==null || slow==null) return false;
return true;
}
}

环形链表
http://example.com/2022/06/06/环形链表/
作者
zlw
发布于
2022年6月6日
许可协议