View RSS Feed

Algorithm and Data Structure

Implementing a Stack in Java

Rate this Entry
by , 02-19-2012 at 07:13 AM (4017 Views)
This post will be explaining the Java’s Stack implementation. Last in first order policy is used in Stack in which one by one elements get inserted in a sequence which could be retrieved later on in reverse order. Use these 2 methods to insert or read the elements to/from the Stack.

• Pop()
• Push()

Code is given below to show the implementation of LIFP stack. Total elements that are needed to be inserted to Stack will be taken and after which it will be asked for those elements which are required to get inserted to Stack.

Java Code: This is the code to explain Stack Implementation in Java
import java.io.*;
import java.util.*;

public class StackImplement{
  Stack<Integer> stack;
  String str;
  int num, n;
  public static void main(String[] args){
  StackImplement q = new StackImplement();
  }
  public StackImplement(){
  try{
  stack = new Stack<Integer>();
  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader bf = new BufferedReader(ir);
  System.out.print("Enter number of elements : ");
  str = bf.readLine();
  num = Integer.parseInt(str);
  for(int i = 1; i <= num; i++){
  System.out.print("Enter elements : ");
  str = bf.readLine();
  n = Integer.parseInt(str);
  stack.push(n);
  }
  }
  catch(IOException e){}
  System.out.print("Retrieved elements from the stack : ");
  while (!stack.empty()){
  System.out.print(stack.pop() + "  ");
  }
  }
}

Submit "Implementing a Stack in Java" to Facebook Submit "Implementing a Stack in Java" to Digg Submit "Implementing a Stack in Java" to del.icio.us Submit "Implementing a Stack in Java" to StumbleUpon Submit "Implementing a Stack in Java" to Google

Tags: java stack Add / Edit Tags
Categories
Stack

Comments