Sunday, February 23, 2014

Stack Program using Arrays in Java!

Stack :

A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: pushthe item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.

Applications :

  1. The simplest application of a stack is to reverse a word. You push a given    word to stack - letter by letter - and then pop letters from the stack.
  2. Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.
  3. Infix to Postfix conversion.

Operations :

  1. Push : To push an element into the stack.
  2. Pop   : To pop an element from the stack.
  3. Peek  : Shows the top most element in the stack.
  4. isEmpty : Determines whether the stack is empty or not.

Java Program!

package adsa;
import java.util.Scanner;
interface StackAdt{
void push() throws Exception;
void pop();
void display();
}
public class StackArr implements StackAdt{
int top;
int stack[];
int size;
Scanner s=new Scanner(System.in);
public StackArr() throws Exception{
System.out.println("Enter the stack size :");
size=s.nextInt();
stack=new int[size];
top=-1;
}
public void push() throws Exception{
if(top==stack.length-1)
System.out.println("Stack is full!!");
else{
System.out.println("Enter the element into the stack :");
int ele=s.nextInt();
top++;
stack[top]=ele;
}
}
public void pop(){
if(top==-1)
System.out.println("Stack underflow!!");
else{
System.out.println("Popped item is :"+stack[top]);
top--;
}

}
public void display(){
System.out.println("The elements in the stack are...");
if(top==-1){
System.out.println("No elements to display!!");
}else
{
for(int i=top;i>=0;i--){
System.out.print(stack[i]);
}
}System.out.println();
}
public static void main(String args[])throws Exception{
Scanner s=new Scanner(System.in);
StackArr st=new StackArr();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("1. Push 2. Pop 3. Display 4. Exit\n Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1:st.push();
break;
case 2: st.pop();
break;
case 3:st.display();
break;
case 4:System.exit(0);
default:System.out.println("Invalid input");
}
System.out.println("Do you want to continue (y/N):");
ch=s.next();
}
}
}

No comments:

Post a Comment