How to Implement Stack in Java



Before we proceed further we need to understand what is Stack all about.
As per Wiki-One way of describing the stack is as a last in, first out (LIFO) abstract data type and linear data structure.

So our objective will be to
1.create a data structure to hold values
2.should be able to insert values in the current position
3.Should be able to remove values from last

For point#1 I will use array.This is easy to understand with Array. Later I will use some advance concept.So we need to create an array and a pointer which will provide me the current position of the array.let us initialize the the pointer to -1 . We need some control to restrict user for the pop without a push. and based on the size we can restrict user to push beyond array capacity.
The starting of the code as follows:


int array_[];
int Stack_pointer_;
int Size_=0;
public void array_set(int Size)
{
array_=new int[Size];
Stack_pointer_=-1;

}
 
Well now we need to implement the point-2 that It should be able to push values to the array..The Steps will be
1. Increment the the pointer by one during push.
2. Insert the value to the corresponding location.

public void push(int number) {
System.out.println("Stack pointer value"+Stack_pointer_);
array_[++Stack_pointer_]=number;
}
 
We will implement the point-3 that It should be able to pop values from the array.Here we need to decrease the pointer during pop. So only we need decrease the stack pointer value by one.

public long pop(){
//Stack_pointer_=Stack_pointer_-1;
System.out.println("Current Stack pointer value"+Stack_pointer_);
return array_[Stack_pointer_--];
}
 
Implementing the different Exception handling the code will look like-for Push

public void push(int number) {
    if (Stack_pointer_
Exception handling the code will look like-for POP

public long  pop(int j){
    //Stack_pointer_=Stack_pointer_-1;
    if(Stack_pointer_==-1)
    {
        System.out.println("You can not pop here");
        return array_[Stack_pointer_];
    }
    else
    {
       System.out.println("Poping "+j+array_[j]);
      return  array_[Stack_pointer_--];
 
    }
   
}
 
The final code will looks like---


import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
public class Calculator {
    int array_[];
    int Stack_pointer_;
    int Size_=0;
public void push(int number) {
 if (Stack_pointer_=0;j--)
        {
            System.out.println("Poping"+j);
            calc.pop(j);
        }
    }
  
}
 
How to Implement Stack in Java How to Implement Stack in Java Reviewed by Animesh Chatterjee on December 21, 2012 Rating: 5

1 comment:

Powered by Blogger.