-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform_queue.cpp
More file actions
131 lines (120 loc) · 2.07 KB
/
transform_queue.cpp
File metadata and controls
131 lines (120 loc) · 2.07 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <iostream>
using namespace std;
#define NULL_VALUE -1
class Node{
public:
Node(){
next = NULL;
}
int data;
Node* next;
};
class Stack{
public:
Stack(){
head = NULL;
}
int push(int);
int pop();
bool isEmpty();
int peek();
private:
Node* head;
};
int Stack::push(int data){
Node* node = new Node;
node->data = data;
node->next = head;
head = node;
}
int Stack::pop(){
if(isEmpty()){
return NULL_VALUE;
}
int data;
data = head->data;
head = head->next;
return data;
}
bool Stack::isEmpty(){
return head == NULL;
}
int Stack::peek(){
if(head != NULL){
return head->data;
}
return NULL_VALUE;
}
class StackedQueue{
public:
StackedQueue(){
stack1 = new Stack();
stack2 = new Stack();
isPushed = false;
}
int push(int);
int pop();
bool isEmpty();
int peek();
private:
int moveToStack1();
int moveToStack2();
Stack* stack1;
Stack* stack2;
bool isPushed;
};
int StackedQueue::moveToStack1(){
if(!isPushed){
while(!stack2->isEmpty()){
stack1->push(stack2->pop());
}
isPushed = true;
}
}
int StackedQueue::moveToStack2(){
if(isPushed){
while(!stack1->isEmpty()){
stack2->push(stack1->pop());
}
isPushed = false;
}
}
int StackedQueue::push(int data){
moveToStack1();
stack1->push(data);
}
int StackedQueue::pop(){
moveToStack2();
return stack2->pop();
}
bool StackedQueue::isEmpty(){
return stack1->isEmpty() && stack2->isEmpty();
}
int StackedQueue::peek(){
moveToStack2();
return stack2->peek();
}
int main(){
StackedQueue* queue = new StackedQueue;
cout << queue->pop() << endl;
cout << queue->pop() << endl;
cout << "is empty?" << endl;
cout << queue->isEmpty() << endl;
queue->push(5);
queue->push(3);
queue->push(6);
cout << "is empty?" << endl;
cout << queue->isEmpty() << endl;
cout << queue->pop() << endl;
cout << queue->pop() << endl;
queue->push(8);
cout << queue->peek() << endl;
cout << queue->pop() << endl;
cout << queue->pop() << endl;
cout << queue->pop() << endl;
cout << queue->pop() << endl;
// Stack* stack = new Stack();
// stack->push(1);
// cout << stack->pop() << endl;
return 0;
}