Stack work

A stack is a LIFO (Last in, first out) data structure.
It can easily be used to reverse the order of a list (see below).
Examples are:

  • The undo/redo feature in a word processing application, e.g. MS Word
  • The back and forward buttons in a browser
  • The call stack of a computer program
package stack;
public class StackApp {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        // add code to reverse the contents of
        // the array, by using the stack
    }
}

class Stack{
    int[] arry = new int[10];
    int ptr =0;

    void push(int n){
        arry[ptr] = n;
        ptr = ptr + 1;
     }

    int pop(){
        if (!isEmpty()){
            ptr = ptr - 1;
            return arry[ptr];
        }
        return -999;
    }

    boolean isEmpty(){
        return ptr == 0;
    }

}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s