linked-list-cycle 1.0.0
Linked List Cycle
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
8struct ListNode
9{
10 int val;
12 ListNode(int x) : val(x), next(NULL) {}
13};
14
15ListNode* create_list(const vector<int>& array, int pos)
16{
17 if (array.size() == 0)
18 return NULL;
19 ListNode* head = new ListNode(array[0]);
20 ListNode* current = head;
21 ListNode* cycling_node = NULL;
22 for (int i = 1; i < (int)array.size(); ++i)
23 {
24 current->next = new ListNode(array[i]);
25 current = current->next;
26 if (i == pos)
27 cycling_node = current;
28 }
29 if (pos == 0)
30 current->next = head;
31 else
32 current->next = cycling_node;
33 return head;
34}
35
37{
38 ListNode* current = head;
39 set<ListNode*> visited;
40 while (current != NULL)
41 {
42 if (visited.find(current) != visited.end())
43 break;
44 visited.insert(current);
45 cout << current->val << endl;
46 current = current->next;
47 }
48 if (current) // if cycle exists
49 cout << "next in cycle: " << current->val << endl;
50}
51
52void delete_list(ListNode* head, set<ListNode*>* handled = NULL)
53{
54 bool created = false;
55 if (!handled)
56 {
57 handled = new set<ListNode*>;
58 created = true;
59 }
60 handled->insert(head);
61 if (handled->find(head->next) == handled->end() && head->next)
62 delete_list(head->next, handled);
63 delete head;
64 if (created)
65 delete handled;
66}
67
69{
70public:
75 {
76 ListNode* current = head;
77 set<ListNode*> visited;
78 while (current != NULL)
79 {
80 if (visited.find(current) != visited.end())
81 return true;
82 visited.insert(current);
83 current = current->next;
84 }
85 return false;
86 }
87
91 bool hasCycle(ListNode* head)
92 {
93 ListNode* fast = head;
94 ListNode* slow = head;
95 while (fast != NULL)
96 {
97 slow = slow->next;
98
99 fast = fast->next;
100 if (fast == NULL)
101 return false;
102
103 fast = fast->next;
104
105 if (slow == fast)
106 return true;
107 }
108 return false;
109 }
110};
111
112int main()
113{
114 vector<int> input = {3,2,0,-4};
115 int pos = 1;
116 ListNode* head = create_list(input, pos);
117 print_list(head);
118
119 cout << "Does the list contain a cycle? " << Solution().hasCycle(head) << endl;
120
121 delete_list(head);
122 return 0;
123}
bool hasCycle(ListNode *head)
Check if the list has a cycle using fast and slow pointers.
Definition main.cpp:91
bool has_cycle_2(ListNode *head)
Check if the list has a cycle using set<ListNode*>
Definition main.cpp:74
ListNode * create_list(const vector< int > &array, int pos)
Definition main.cpp:15
void delete_list(ListNode *head, set< ListNode * > *handled=NULL)
Definition main.cpp:52
void print_list(ListNode *head)
Definition main.cpp:36
int main()
Definition main.cpp:112
Definition for singly-linked list.
Definition main.cpp:9
int val
Definition main.cpp:10
ListNode(int x)
Definition main.cpp:12
ListNode * next
Definition main.cpp:11