Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface IntStack {
- void push(int item);
- int pop();
- }
- class Stack implements IntStack {
- private int stck[];
- private int tos;
- Stack(int size) {
- stck = new int[size];
- tos = -1;
- }
- public boolean isEmpty(){
- if(tos > -1){
- return false;
- }
- return true;
- }
- // Push
- public void push(int item) {
- if(tos==stck.length-1)
- System.out.println("Stack is full.");
- else
- stck[++tos] = item;
- }
- // Pop
- public int pop() {
- if(tos < 0) {
- System.out.println("Stack underflow.");
- return 0;
- }
- else
- return stck[tos--];
- }
- }
- class Queue {
- Stack st1, st2;
- Queue(){
- st1 = new Stack(5);
- st2 = new Stack(5);
- }
- boolean isEmpty(){
- return st1.isEmpty();
- }
- void enqueue(int x){
- st1.push(x);
- }
- int dequeue(){
- int x, ret;
- if(st1.isEmpty()){
- System.out.println("Queue underflow.");
- return 0;
- }
- while(!st1.isEmpty()){
- x = st1.pop();
- st2.push(x);
- }
- ret = st2.pop();
- while(!st2.isEmpty()){
- x = st2.pop();
- st1.push(x);
- }
- return ret;
- }
- }
- class Main {
- public static void main(String[] args) {
- Queue a = new Queue();
- a.enqueue(5);
- a.enqueue(6);
- a.enqueue(7);
- a.dequeue();
- a.enqueue(10);
- while(!a.isEmpty()){
- System.out.print(a.dequeue() + " ");
- }
- System.out.print("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment