-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathQueue_Stack.java
119 lines (92 loc) · 1.87 KB
/
Queue_Stack.java
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
import java.util.*;
public class Queue_Stack {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Queue_St q=new Queue_St();
boolean flag=true;
int valu=0;
while(flag) {
System.out.println("1. Enqueue()");
System.out.println("2. Dequeue()");
System.out.println("3. Current size of queue");
System.out.println("4. peek()");
System.out.println("5. View queue");
System.out.println("6. Exit");
System.out.println("Enter Choice");
int choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter value");
valu=sc.nextInt();
q.enqueue(valu);
break;
case 2: System.out.println(q.dequeue());
break;
case 3: System.out.println(q.count());
break;
case 4: System.out.println(q.peek());
break;
case 5:q.viewQ();
break;
case 6: flag=false;
break;
default: System.out.println("invalid choice");
}//switch
System.out.println();
}//while
}
}
class Queue_St{
Stack<Integer> st1;
Stack<Integer> st2;
int size;
int peek;
public Queue_St(){
st1=new Stack();
st2=new Stack();
size=0;
peek=0;
}
public int count() {
return size;
}
public boolean isEmpty() {
return(st1.isEmpty() && st2.isEmpty());
}
public void enqueue(int val) {
if(size==0)
peek=val;
st1.push(val);
size++;
}
public int dequeue() {
if(isEmpty()) {
System.out.println("Queue is empty");
return -999;
}
else {
while(!st1.isEmpty()) {
st2.push(st1.pop());
}
size--;
int pop= st2.pop();
peek=st2.peek();
while(!st2.isEmpty()) {
st1.push(st2.pop());
}
return pop;
}
}
public int peek() {
return peek;
}
public void viewQ() {
if(isEmpty()) {
System.out.println("Queue is empty");
return;
}
else
{
System.out.println(String.valueOf(st1));
}
}
}