- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Linked List Cycle II in C++
Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list
To solve this, we will follow these steps −
- slow := head and fast := head
- while slow, fast and next of fast is available, then
- slow := next of slow
- fast := next of (next of fast)
- if slow = fast, then break
- if fast is not empty or next of first is not empty, then return null
- if slow = fast, then
- slow := head
- while slow is not same as fast
- slow := next of slow and fast := next of fast
- return slow
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int data){ val = data; next = NULL; } }; ListNode *make_list(vector<int> v){ ListNode *head = new ListNode(v[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } ListNode *get_node(ListNode *head, int pos){ ListNode *ptr = head; if(pos != -1){ int p = 0; while(p < pos){ ptr = ptr->next; p++; } return ptr; } return NULL; } class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode* slow = head; ListNode* fast = head; while(slow && fast && fast->next){ slow = slow->next; fast = fast->next->next; if(slow == fast)break; } if(!fast || !fast->next)return NULL; if(slow == fast){ slow = head; while(slow!=fast){ slow = slow->next; fast = fast->next; } } return slow; } }; main(){ Solution ob; vector<int> v = {5,3,2,0,-4,7}; ListNode *head = make_list(v); int pos = 1; ListNode *lastNode = get_node(head, v.size() - 1); lastNode->next = get_node(head, pos); cout << "Tail is connected to the node with value:" <<ob.detectCycle(head)->val; }
Input
[5,3,2,0,-4,7] 1
Output
Tail is connected to the node with value:3
Advertisements