File tree Expand file tree Collapse file tree 1 file changed +116
-0
lines changed
Data Structures/Linked Lists/Circular Linked Lists Expand file tree Collapse file tree 1 file changed +116
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ This is a Circular Linked List program which reverses the Linked List iteratively.
4
+
5
+ Since, it is a Circular Linked List, the last node would point to the head node.
6
+
7
+ */
8
+
9
+ #include < iostream>
10
+
11
+ using namespace std ;
12
+
13
+ /*
14
+
15
+ Node definition:
16
+ 1. Integer Data
17
+ 2. Pointer to next node.
18
+
19
+ */
20
+
21
+ class cll_node {
22
+ public:
23
+ int data;
24
+ cll_node* next;
25
+ };
26
+
27
+ void createCLL (cll_node* &head) {
28
+
29
+ int choice;
30
+
31
+ cll_node* temp = head;
32
+
33
+ do {
34
+ int data;
35
+
36
+ cout << " Enter Data : " ;
37
+ cin >> data;
38
+
39
+ cll_node* newNode = new cll_node ();
40
+ newNode->data = data;
41
+ newNode->next = NULL ;
42
+
43
+ if (head == NULL ) {
44
+ head = newNode;
45
+ newNode->next = head;
46
+ temp = head;
47
+ } else {
48
+ temp->next = newNode;
49
+ temp = newNode;
50
+ temp->next = head;
51
+ }
52
+
53
+ cout << " Do you want to continue? (1/0) : " ;
54
+ cin >> choice;
55
+
56
+ } while (choice == 1 );
57
+
58
+ }
59
+
60
+ void reverse_it (cll_node* &head , cll_node* p) {
61
+
62
+ cll_node *q = head , *r = head->next ;
63
+
64
+ while (r != head) {
65
+ q->next = p;
66
+ p = q;
67
+ q = r;
68
+ r = r->next ;
69
+ }
70
+ q->next = p;
71
+ head = q;
72
+
73
+ }
74
+
75
+ void reverse (cll_node* &head) {
76
+ if (head == NULL || head->next == head)
77
+ return ;
78
+
79
+ cll_node* temp = head;
80
+ while (temp->next != head) {
81
+ temp = temp->next ;
82
+ }
83
+
84
+ reverse_it (head , temp);
85
+
86
+ }
87
+
88
+ void display (cll_node* head) {
89
+ cout << " The elements are : " ;
90
+ if (head == NULL )
91
+ return ;
92
+ cll_node* temp = head;
93
+
94
+ do {
95
+ cout << temp->data << " " ;
96
+ temp = temp->next ;
97
+ } while (temp != head);
98
+ cout << endl;
99
+ }
100
+
101
+ int main () {
102
+
103
+ cll_node* head = NULL ;
104
+
105
+ createCLL (head);
106
+
107
+ cout << " Before Reversing : " << endl;
108
+ display (head);
109
+
110
+ reverse (head);
111
+
112
+ cout << " After Reversing : " << endl;
113
+ display (head);
114
+
115
+ return 0 ;
116
+ }
You can’t perform that action at this time.
0 commit comments