Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0ad09af

Browse files
committed
Completed Queue using Stack prog
1 parent 455bb4a commit 0ad09af

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

‎src/stacks_queues/QueueUsingStacks.java‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,53 @@
11
package stacks_queues;
22

3+
import java.util.Stack;
4+
35
public class QueueUsingStacks {
6+
7+
Stack<Integer> stack1 = new Stack<Integer>();
8+
Stack<Integer> stack2 = new Stack<Integer>();
9+
10+
void enqueue(int data) {
11+
stack1.push(data);
12+
}
13+
14+
boolean isEmpty() {
15+
return stack1.size() + stack2.size() == 0;
16+
}
17+
18+
int dequeue() throws Exception {
19+
if(isEmpty()) {
20+
throw new Exception("queue is empty");
21+
}
22+
23+
if(stack2.isEmpty()) {
24+
while(!stack1.isEmpty()){
25+
stack2.push(stack1.pop());
26+
}
27+
}
28+
29+
return stack2.pop();
30+
}
31+
32+
33+
public static void main(String[] args) throws Exception {
34+
35+
QueueUsingStacks q1 = new QueueUsingStacks();
36+
37+
q1.enqueue(1);
38+
q1.enqueue(2);
39+
q1.enqueue(3);
40+
41+
System.out.println(q1.dequeue());
42+
System.out.println(q1.dequeue());
43+
44+
q1.enqueue(4);
45+
q1.enqueue(5);
46+
q1.enqueue(6);
47+
48+
System.out.println(q1.dequeue());
49+
System.out.println(q1.dequeue());
450

5-
public static void main(String[] args) {
6-
// TODO Auto-generated method stub
751

852
}
953

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /