View RSS Feed

Algorithm and Data Structure

Java Stack Introduction

Rate this Entry
by , 02-19-2012 at 08:11 AM (1020 Views)
A stack is basically a data structure which uses the following:

  • Methods for inserting the data by the help of push operation
  • Methods for removal of data by the help of pop operation.


Peak method is supported by Stack implementations. It will make the head to be read without removal from Stack. Last in First out policy is used in Stack. This means that data which has been inserted in data structure at last will be made to get removed first.

Data will be placed at head when data is inserted into Stack. First, data will remove from Stack. This process could be better explained by this given figure:

Name:  1.JPG
Views: 121
Size:  5.5 KB

Before push operation. After push operation.


Name:  1.JPG
Views: 116
Size:  5.8 KB

Before pop operation. After pop operation

Stack implementation is provided by Java in form of java.util.Stack. Stack operations are explained by this code:

Java Code: This is the code to explain Java Stack
import java.util.Stack;

public class MyStackDemo
{
        public static void main(String args[])
        {
                // Create a new, empty stack
                Stack lifo = new Stack();

                // Let's add some items to it
                for (int i = 1; i <= 10; i++)
                {
                        lifo.push ( new Integer(i) );
                }

                // Last in first out means reverse order
                while ( !lifo.empty() )
                {
                        System.out.print ( lifo.pop() );
                        System.out.print ( ',' );
                }

                // Empty, let's lift off!
                System.out.println (" LIFT-OFF!");
        }

}

Submit "Java Stack Introduction" to Facebook Submit "Java Stack Introduction" to Digg Submit "Java Stack Introduction" to del.icio.us Submit "Java Stack Introduction" to StumbleUpon Submit "Java Stack Introduction" to Google

Tags: stack Add / Edit Tags
Categories
Queue , Stack

Comments