@@ -14,7 +14,7 @@ class Node // class to create a node
14
14
}
15
15
};
16
16
17
- class List
17
+ class List // class to add, delete, print and search nodes
18
18
{
19
19
Node *head;
20
20
Node *tail;
@@ -25,7 +25,7 @@ class List
25
25
head = tail = NULL ;
26
26
}
27
27
28
- void push_front (int val)
28
+ void push_front (int val) // add node on front of linked list
29
29
{
30
30
Node *newNode = new Node (val);
31
31
@@ -41,28 +41,132 @@ class List
41
41
}
42
42
}
43
43
44
- void printLL ()
44
+ void push_back (int val) // add node on back or end of linked list
45
+ {
46
+ Node *newNode = new Node (val);
47
+
48
+ if (head == NULL ) // empty linked list
49
+ {
50
+ head = tail = newNode;
51
+ return ;
52
+ }
53
+ else // not empty
54
+ {
55
+ tail->next = newNode;
56
+ tail = newNode;
57
+ }
58
+ }
59
+
60
+ void pop_front () // delete node from front of linked list
61
+ {
62
+ if (head == NULL ) // empty linked list
63
+ {
64
+ cout << " LL is empty\n " ;
65
+ return ;
66
+ }
67
+
68
+ Node *temp = head;
69
+ head = head->next ;
70
+ temp->next = NULL ;
71
+
72
+ delete temp;
73
+ }
74
+
75
+ void pop_back () // delete node from back or end of linked list
76
+ {
77
+ if (head == NULL ) // empty linked list
78
+ {
79
+ cout << " LL is empty\n " ;
80
+ return ;
81
+ }
82
+
83
+ Node *temp = head;
84
+ while (temp->next != tail)
85
+ {
86
+ temp = temp->next ;
87
+ }
88
+
89
+ temp->next = NULL ;
90
+ delete tail;
91
+ tail = temp;
92
+ }
93
+
94
+ void insert (int val, int pos) // to insert or add a node at specific position
95
+ {
96
+ if (pos < 0 )
97
+ {
98
+ cout << " Invalid position\n " ;
99
+ return ;
100
+ }
101
+
102
+ if (pos == 0 )
103
+ {
104
+ push_front (val);
105
+ return ;
106
+ }
107
+
108
+ Node *temp = head;
109
+ for (int i = 0 ; i < pos - 1 ; i++)
110
+ {
111
+ if (temp == NULL )
112
+ {
113
+ cout << " Invalid position\n " ;
114
+ return ;
115
+ }
116
+
117
+ temp = temp->next ;
118
+ }
119
+
120
+ Node *newNode = new Node (val);
121
+ newNode->next = temp->next ;
122
+ temp->next = newNode;
123
+ }
124
+
125
+ void printLL () // to print linked list
45
126
{
46
127
Node *temp = head;
47
128
48
129
while (temp != NULL )
49
130
{
50
- cout << temp->data << " -> " ;
131
+ cout << temp->data << " -> " ;
51
132
temp = temp->next ;
52
133
}
53
134
cout << " NULL" << endl;
54
135
}
136
+
137
+ int search (int key) // to search a node
138
+ {
139
+ Node *temp = head;
140
+ int idx = 0 ;
141
+
142
+ while (temp != NULL )
143
+ {
144
+ if (temp->data == key)
145
+ {
146
+ return idx;
147
+ }
148
+
149
+ temp = temp->next ;
150
+ idx++;
151
+ }
152
+
153
+ return -1 ;
154
+ }
55
155
};
56
156
57
157
int main ()
58
158
{
59
159
List ll;
60
160
61
- ll.push_front (1 );
62
- ll.push_front (2 );
63
161
ll.push_front (3 );
162
+ ll.push_front (2 );
163
+ ll.push_front (1 );
164
+
165
+ ll.insert (4 , 1 );
64
166
65
167
ll.printLL ();
66
168
169
+ cout << ll.search (2 ) << endl;
170
+
67
171
return 0 ;
68
172
}
0 commit comments