fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct ListNode {
  5. int value;
  6. ListNode* prev;
  7. ListNode* next;
  8. ListNode(int val) : value(val), prev(nullptr), next(nullptr) {}
  9. };
  10.  
  11. bool hasCycle(ListNode* head) {
  12. ListNode* current = head;
  13.  
  14. // Checking the base case whether DL is Circular DL or not
  15. // If the DL is circular with just head->prev nullptr but tail->next = head : This case will be checked in while loop
  16. if(current->prev != nullptr) return true;
  17. while (current->next != nullptr) {
  18. // If the previous node of the next node is not the current node itself,
  19. // it indicates the presence of a loop
  20. if (current->next->prev != current) {
  21. return true;
  22. }
  23. current = current->next;
  24. }
  25. // If traversal completes without encountering a loop, we return false
  26. return false;
  27. }
  28.  
  29. //function to print the doubly linked list
  30. void printList(ListNode* head) {
  31. ListNode* current = head;
  32. while (current != nullptr) {
  33. cout << current->value << " ";
  34. current = current->next;
  35. }
  36. cout <<endl;
  37. }
  38.  
  39. int main() {
  40. ListNode* node1 = new ListNode(1);
  41. ListNode* node2 = new ListNode(2);
  42. ListNode* node3 = new ListNode(3);
  43. ListNode* node4 = new ListNode(4);
  44.  
  45. node1->next = node2;
  46. node2->prev = node1;
  47. node2->next = node3;
  48. node3->prev = node2;
  49. node3->next = node4;
  50. node4->prev = node3;
  51. node4->next = node2; // Cycle back to node2
  52.  
  53. cout << (hasCycle(node1) ? "list contain a cycle" : "list does not contain a cycle") <<endl;
  54.  
  55. // Freeing memory
  56. delete node1;
  57. delete node2;
  58. delete node3;
  59. delete node4;
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5236KB
stdin
Standard input is empty
stdout
list contain a cycle