环形链表【LC141】
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/linked-list/jbex5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
快慢指针
-
思路
使用快慢指针,快指针每次移动两个位置,慢指针每次移动一个位置,如果链表存在环,那么快慢指针会相遇
-
2021/12/8
-
2022/09/22
-
2023/07/29
/*** 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) {if(head==null){return false;}ListNode slowIndex = head;ListNode fastIndex = head;while(fastIndex != null && fastIndex.next != null){fastIndex = fastIndex.next.next;slowIndex = slowIndex.next;if(slowIndex == fastIndex){return true;}}return false;} }
public class Solution {public boolean hasCycle(ListNode head) {if (head == null || head.next == null) {return false;}ListNode slow = head;ListNode fast = head.next;while (slow != fast) {if (fast == null || fast.next == null) {return false;}slow = slow.next;fast = fast.next.next;}return true;} }作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
-
复杂度分析
-
时间复杂度: O ( N ) O(N) O(N),其中 N是链表中的节点数。
-
空间复杂度: O ( 1 ) O(1) O(1)。
-
哈希表
最容易想到的方法是遍历所有节点,每次遍历到一个节点时,判断该节点此前是否被访问过。
具体地,我们可以使用哈希表来存储所有已经访问过的节点。每次我们到达一个节点,如果该节点已经存在于哈希表中,则说明该链表是环形链表,否则就将该节点加入哈希表中。重复这一过程,直到我们遍历完整个链表即可。
public class Solution {public boolean hasCycle(ListNode head) {Set<ListNode> seen = new HashSet<ListNode>();while (head != null) {if (!seen.add(head)) {return true;}head = head.next;}return false;}
}
- 复杂度分析
- 时间复杂度: O ( N ) O(N) O(N),其中 N是链表中的节点数
- 空间复杂度: O ( N ) O(N) O(N)