#include <iostream>
using namespace std;
struct ListNode {
int value;
ListNode* prev;
ListNode* next;
ListNode(int val) : value(val), prev(nullptr), next(nullptr) {}
};
bool hasCycle(ListNode* head) {
ListNode* current = head;
// Checking the base case whether DL is Circular DL or not
// If the DL is circular with just head->prev nullptr but tail->next = head : This case will be checked in while loop
if(current->prev != nullptr) return true;
while (current->next != nullptr) {
// If the previous node of the next node is not the current node itself,
// it indicates the presence of a loop
if (current->next->prev != current) {
return true;
}
current = current->next;
}
// If traversal completes without encountering a loop, we return false
return false;
}
//function to print the doubly linked list
void printList(ListNode* head) {
ListNode* current = head;
while (current != nullptr) {
cout << current->value << " ";
current = current->next;
}
cout <<endl;
}
int main() {
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
node1->next = node2;
node2->prev = node1;
node2->next = node3;
node3->prev = node2;
node3->next = node4;
node4->prev = node3;
node4->next = node2; // Cycle back to node2
cout << (hasCycle(node1) ? "list contain a cycle" : "list does not contain a cycle") <<endl;
// Freeing memory
delete node1;
delete node2;
delete node3;
delete node4;
return 0;
}