Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Topic describes
Given a linked list, determine whether there are rings in the list.
If there is a node in the list that can be reached again by following the next pointer continuously, then there is a ring in the list. To represent the rings in a given list, we use the integer pos to represent where in the list the tail joins (the index starts at 0). If pos is -1, there are no rings in the linked list. Note: POS is not passed as an argument, just to identify the actual state of the linked list.
Returns true if there are rings in the list. Otherwise, return false.
Advanced:
Can you solve this problem with O(1) (i.e., constant) memory?
Example 1: input: head = [3,2,0,-4], pos = 1 output: true explanation: there is a ring in the linked list whose tail is connected to a second node. Example 2: input: head = [1,2], pos = 0 output: true explanation: there is a ring in the linked list whose tail is connected to the first node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There are no loops in the linked list. Source: LeetCode Link: https://leetcode-cn.com/problems/linked-list-cycle Copyright belongs to The Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.Copy the code
Thought analysis
- Today’s algorithm is to determine whether a linked list has a ring. In short, is the node has been repeated.
- First, we can use hashSet to record the number of occurrences of each node. If a node appears twice, it is looped.
- Use the fast and slow Pointers. If the fast and slow Pointers are the same, it indicates that there is a loop.
Through the code
- A hashMap solution
/** * 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 || head.next == null) {
return false;
}
Set<ListNode> set = new HashSet<>();
while(head ! =null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false; }}Copy the code
- Fast and slow pointer solution
/** * 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 || 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; }}Copy the code
conclusion
- The time complexity of the hashSet solution is O(n) and the space complexity is O(n).
- The time complexity of the fast and slow pointer solution is O(n) and the space complexity is O(1).
- Adhere to the algorithm of the day, come on!