Monday, April 4, 2011

Stack Data Structure in JAVA

stack data structure in java
A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The push operation adds an item to the top of the stack, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation removes an item from the top of the stack, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty stack.

A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition: therefore, the lower elements are those that have been on the stack the longest

Now let the code talk...
class Olink{
 Object arr[];
 int Size;

 Olink(int Size_Stack){
  arr=new Object[Size_Stack];
  Size=0;
 }
 boolean chk_full(){
  return Size==arr.length;
 }
 boolean chk_empty(){
  return Size==0;
 }
 void push(Object d){
  if(!(chk_full())) arr[Size++]=d;
  else System.out.println("Stack Full !");
 }
 Object pop(){
  if(!(chk_empty())) return arr[--Size];
  else {
   System.out.println("Stack Empty !");
   return null;
  }
 }
 Object peek(){
  if(!(chk_empty())) return arr[Size];
  else {
   System.out.println("Stack Empty");
   return null;
  }
 }
 void show(){
  for (int i=0;i<Size;i++){
   System.out.print(arr[i]+" ");
  }
 }
}
class StackArray{
 public static void main(String [] nix){
  Olink o=new Olink(10);
  o.push(1);
  o.push(2);
  o.push(3);
  o.push(4);
  o.push(5);
  o.push(6);
  o.push(7);
  o.push(8);
  o.push(9);
  o.push(10);
  o.push(11);
  System.out.println("pop : "+o.pop());
  System.out.println("pop : "+o.pop());
  System.out.println("pop : "+o.pop());
  o.show();
 }
}
Firstly we create a stack of size 10 and then push a value on it by pushing we just increment the value of size variable until its value equals to array length, once it is full no value is inserted, to pop a value out from the stack we just decrement the value of size variable and return the value, peek will give the value that will be pop out next.

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems