-
Notifications
You must be signed in to change notification settings - Fork 0
/
circularLL.cpp
123 lines (99 loc) · 2.6 KB
/
circularLL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
using namespace std;
// Define the Node class
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(NULL) {}
};
// Function to check if the linked list is circular
bool isCircular(Node* head) {
if (head == NULL) return true; // Consider an empty list as circular
Node* temp = head->next; // Start traversal from the node after head
// Traverse the list to check if we can reach head again
while (temp != NULL && temp != head) {
temp = temp->next; // Move to the next node
}
// If we have reached head again, the list is circular
return temp == head;
}
// Function to print the list
void printList(Node* head) {
if (head == NULL) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
cout << "List: ";
Node* start = head;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
// Stop if we return to the starting node in a circular list
if (temp == start) {
cout << "(back to head)" << endl;
return;
}
}
cout << "NULL" << endl;
}
// Function to append a new node to the list
void appendNode(Node*& head, int value) {
Node* newNode = new Node(value);
if (head == NULL) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to create a circular link
void createCircular(Node* head) {
if (head == NULL) return;
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
// Create the circular link
temp->next = head;
}
// Function to delete the list
void deleteList(Node* head) {
if (head == NULL) return;
Node* temp = head;
Node* nextNode;
// Traverse the list and delete nodes
while (temp->next != head) {
nextNode = temp->next;
delete temp;
temp = nextNode;
}
// Delete the last node
delete temp;
}
int main() {
Node* head = NULL;
// Insert elements into the list
appendNode(head, 1);
appendNode(head, 2);
appendNode(head, 3);
appendNode(head, 3);
// Uncomment to create a circular link
createCircular(head);
// Print the list
printList(head);
// Check and print if the list is circular
bool circular = isCircular(head);
if (circular) {
cout << "The list is circular." << endl;
} else {
cout << "The list is not circular." << endl;
}
// Clean up
deleteList(head);
return 0;
}