How to solve the Ring problem in single linked list by C++
This article is a detailed introduction to "C++ how to solve the ring problem in a single-linked list". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "C++ how to solve the ring problem in a single-linked list" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of the small editor.
A loop in a single-stranded list
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
This problem is a classic application of the speed pointer. Just set up two pointers, a slow pointer that goes one step at a time and a fast pointer that goes two steps at a time. If there are rings in the list, the two pointers will eventually meet. It's so clever, I wouldn't have thought of it. The code is as follows:
C++ solution:
class Solution {public: bool hasCycle(ListNode *head) { ListNode *slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }};
Java solution:
public class Solution { public boolean hasCycle(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; }} Read here, this article "C++ how to solve the ring problem in the single-linked list" article has been introduced, want to master the knowledge points of this article also need to be used by yourself to understand, if you want to know more related content of the article, welcome to pay attention to the industry information channel.