Sunday, 26 January 2014

Post 12: Stacks and Queues

Alright, today I want to show you an implementation of a Stack and a Queue. First of all what is a Stack and a Queue? Well, both are Arrays. But contrary to "ordinary" Arrays you have only limited access to the Array's items. For example in an ordinary Array you can pretty much access all it's members in order to display, add or delete the items. In Stacks or Queues you just can't do it.

Stacks

In Stacks you can only add (or also called "push") and a new item in the very end of the Array. And you can only delete (or also called "pop") the last item of the Array. this is called Last-In-First-Out (LIFO).

Here's the push implementation:

public void push(String input){
        //check whether the stack is full
        if (topOfStack+1< stackSize){
            topOfStack++;
            theStack[topOfStack]=input;
            displayContent();
        }else{
            System.out.println("Stack is full!");
        }
    }

Here's the pop implementation:

public void pop(){
        //if there is something to delete (=pop)
        if (topOfStack>-1){
            theStack[topOfStack]="-1";
            displayContent();
        }else{
            System.out.println("Nothing to delete");
        }
    }

Queue

In Queues you can also only add (or also called "enqueue") a new item at the very end of the Array. But you can only delete (or also called "dequeue") the first item. This is called First-In-First-Out (FIFO).

Here's the enqueue implementation:

public void enqueue(String input){
        //if there's still place in the queue Array
        if (queueLength< queueSize){
            queueLength++;
            String[] inputQ=new String[queueSize];
            inputQ[0]=input;
            String[] tempQ=new String[queueSize];
            tempQ=theQueue;

            //theQueue=ArrayUtils.addAll(inputQ, tempQ);
            //merege
            for (int j=1; j< queueSize; j++){
                inputQ[j]=theQueue[j-1];
            }
            theQueue=inputQ;
            displayQueue();
        }else{
            System.out.println("Queue is full");
        }
    }


Here's the dequeue implementation:

public void dequeue(){
        //if there's still something in the queue
        if (queueLength>0){
            theQueue[queueLength]="-1";
            queueLength--;
            displayQueue();
        }else{
            System.out.println("Queue is empty");
        }
    }

You can see the complete JAVA program here on GitHub.
Tweet