-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinkedlist_based_queue.cpp
More file actions
113 lines (103 loc) · 1.92 KB
/
linkedlist_based_queue.cpp
File metadata and controls
113 lines (103 loc) · 1.92 KB
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
#include <iostream>
using namespace std;
class Node {
public:
int x;
Node* next;
Node() {
next = NULL;
}
Node(int k){
x = k;
next = NULL;
}
};
class Queue {
public:
Node* head;
Node* top;
Node* last;
int len;
Queue(){
head = NULL;
top = NULL;
last = NULL;
len = 0;
}
// Here, I am doing insertion at the end but with the time complexity of O(1) by having a Node (last)
// which has the address of the last element;
void enque(int k){
if(len == 0){
last = new Node(k);
last->next = NULL;
head = last;
top = last;
len++;
return;
}
if(len == 1){
Node* sub = new Node(k);
last->next = sub;
sub->next = NULL;
last = sub;
len++;
head->next = last;
return;
}
Node* sub = new Node(k);
last->next = sub;
sub->next = NULL;
last = sub;
len++;
}
void deque(){
if(len == 0){cout << "Empty Queue, deletion not possible!!" << endl; return;}
if(len == 1){head = NULL; top = NULL; last = NULL; len = 0;return;}
head = head->next;
len-- ;
}
void lens(){
cout << "length of queue is " << len << endl;
}
void print(){
if(len==0) {cout << "Empty Queue " << endl;return;}
Node* temp;
temp = head;
cout << "the first element is the front element of the stack" << endl;
while(temp!=NULL){
cout << temp->x << endl;
temp = temp->next;
}
}
void front(){
cout << "the first element of the queue is " << head->x << endl;
}
};
int main(){
int n;
cout << "enter the number of elements of Queue" << endl;
cin >> n;
Queue q;
for(int i=0;i<n;i++){
cout << "enter it" << endl;
int k;
cin >> k ;
q.enque(k);
}
q.front();
q.print();
q.lens();
q.deque();
q.print();
q.lens();
q.deque();
q.deque();
q.deque();
q.deque();
q.print();
q.lens();
q.deque();
q.enque(2);
q.lens();
q.print();
}