Monday, 12 January 2015

Implementation of Queue with Stack in Java

Something that I wrote for a lab exam.


import java.util.Scanner;

class QueueStack{

    public static void main(String[] args){

        Scanner myScan = new Scanner(System.in);
        System.out.print("Enter the size of Queue: ");
        int input = myScan.nextInt();

        Stack myStack = new Stack(input);



        for(int i = 0; i < input; i++){

            System.out.print("Enter the Element: ");
            int element = myScan.nextInt();
            insert(element, myStack);
        }
        for(int i = 0; i < input; i++){

            System.out.println(myStack.pop());
        }
    }

    public static void insert(int element, Stack stack){

        if (!stack.empty()) {
            int topElement = stack.pop();
            insert(element, stack);
            stack.push(topElement);
        }
        else
            stack.push(element);
    }
}

class Stack{

    int maxSize;
    int top;
    int num_arr[];

    public Stack(int size){

        this.maxSize = size;
        num_arr = new int[maxSize];
        this.top = 0;
    }

    public boolean empty(){

        if(top == 0){

            return true;
        }
        else{
            return false;
        }
    }

    public void push(int passed_input){

        if(top >= maxSize){

            System.out.println("Stack Overflow!");
        }
        else{
            num_arr[top] = passed_input;
            top++;
        }
    }

    public int pop(){

        if(!this.empty()){

            int temp = this.peek();
            num_arr[top - 1] = 0;
            top--;
            return temp;
        }
        else{
            return 0;
        }
    }

    public int peek(){

        if(!this.empty()){

                        return num_arr[top - 1];
                }
                else{
                        return 0;
                }
    }
}

No comments:

Post a Comment