TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
doubly_linked_list.cpp
1#include <cstdio>
2#include <cstdlib>
3#include <iostream>
4
5struct node {
6 int val;
7 node *prev;
8 node *next;
9} * start;
10
12 public:
13 double_linked_list() { start = NULL; }
14 void insert(int x);
15 void remove(int x);
16 void search(int x);
17 void show();
18 void reverseShow();
19};
20
21void double_linked_list::insert(int x) {
22 node *t = start;
23 if (start != NULL) {
24 while (t->next != NULL) {
25 t = t->next;
26 }
27 node *n = new node;
28 t->next = n;
29 n->prev = t;
30 n->val = x;
31 n->next = NULL;
32 } else {
33 node *n = new node;
34 n->val = x;
35 n->prev = NULL;
36 n->next = NULL;
37 start = n;
38 }
39}
40
41void double_linked_list::remove(int x) {
42 node *t = start;
43 while (t != NULL && t->val != x) {
44 t = t->next;
45 }
46 if (t == NULL) {
47 return;
48 }
49 if (t->prev == NULL) {
50 if (t->next == NULL) {
51 start = NULL;
52 } else {
53 start = t->next;
54 start->prev = NULL;
55 }
56 } else if (t->next == NULL) {
57 t->prev->next = NULL;
58 } else {
59 t->prev->next = t->next;
60 t->next->prev = t->prev;
61 }
62 delete t;
63}
64
65void double_linked_list::search(int x) {
66 node *t = start;
67 int found = 0;
68 while (t != NULL) {
69 if (t->val == x) {
70 std::cout << "\nFound";
71 found = 1;
72 break;
73 }
74 t = t->next;
75 }
76 if (found == 0) {
77 std::cout << "\nNot Found";
78 }
79}
80
81void double_linked_list::show() {
82 node *t = start;
83 while (t != NULL) {
84 std::cout << t->val << "\t";
85 t = t->next;
86 }
87}
88
89void double_linked_list::reverseShow() {
90 node *t = start;
91 while (t != NULL && t->next != NULL) {
92 t = t->next;
93 }
94 while (t != NULL) {
95 std::cout << t->val << "\t";
96 t = t->prev;
97 }
98}
99
100int main() {
101 int choice, x;
103 do {
104 std::cout << "\n1. Insert";
105 std::cout << "\n2. Delete";
106 std::cout << "\n3. Search";
107 std::cout << "\n4. Forward print";
108 std::cout << "\n5. Reverse print";
109 std::cout << "\n\nEnter you choice : ";
110 std::cin >> choice;
111 switch (choice) {
112 case 1:
113 std::cout << "\nEnter the element to be inserted : ";
114 std::cin >> x;
115 ob.insert(x);
116 break;
117 case 2:
118 std::cout << "\nEnter the element to be removed : ";
119 std::cin >> x;
120 ob.remove(x);
121 break;
122 case 3:
123 std::cout << "\nEnter the element to be searched : ";
124 std::cin >> x;
125 ob.search(x);
126 break;
127 case 4:
128 ob.show();
129 break;
130 case 5:
131 ob.reverseShow();
132 break;
133 }
134 } while (choice != 0);
135 return 0;
136}
struct node { int data; int height; struct node *left; struct node *right;} node
for std::queue
Definition avltree.cpp:13
int main()
Main function.
for std::assert