-
Notifications
You must be signed in to change notification settings - Fork 690
/
StackQueue.js
49 lines (43 loc) · 888 Bytes
/
StackQueue.js
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
//Queue implm. using 2 stacks
class StackQueue {
constructor() {
this.enqueueStack = [];
this.dequeueStack = [];
this.size = 0;
this.lastOper = 1;
}
enqueue(data) {
if(this.lastOper == 0){
this.deqToEnq();
this.lastOper = 1;
}
this.size++;
this.enqueueStack.push(data);
}
dequeue() {
if(this.lastOper == 1){
this.enqToDeq();
this.lastOper = 0;
}
if(this.howBig() == 0){
return null;
}
this.size--;
return this.dequeueStack.pop();
}
deqToEnq() {
//Move dequeue to enqueue;
for(let i = 0; i < this.size; i++) {
this.enqueueStack.push(this.dequeueStack.pop());
}
}
enqToDeq(){
//Move enqueue to dequeue
for(let i = 0; i < this.size; i++){
this.dequeueStack.push(this.enqueueStack.pop());
}
}
howBig(){
return this.size;
}
}