Java Program for Stack using PUSH and POP

Saturday, 14 January 2012



Program to show stack using PUSH and POP without user input.
import java.util.*;
class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } }
OUTPUT : 

stack: [ ] 
push(42) 
stack: [42] 
push(66) 
stack: [42, 66] 
push(99) 
stack: [42, 66, 99] 
pop -> 99 
stack: [42, 66] 
pop -> 66 
stack: [42] 
pop -> 42 
stack: [ ] 
pop -> empty stack

Program to show stack using PUSH and POP with user input.

import java.io.*;
import java.util.Stack;
public class Stacks {
public static void main(String args[])throws IOException {
DataInputStream k=new DataInputStream(System.in);
Stack r=new Stack();
for(int i=1; i<=3; i++) {
System.out.print(" ");
System.out.print("Enter a value to PUSH: ");
int x=Integer.parseInt(k.readLine());
r.push (new Integer(x) );
System.out.print("Stacked: "+r+"\n");

}System.out.println("STACK IS FULL!");
do {
for(int i=1; i<=3; i++) {
System.out.print(" "
);
System.out.print("Enter a value to POP: ");
int x=Integer.parseInt(k.readLine());
r.pop();
System.out.print("Stacked: "+r+"\n");
}
}while(!r.empty());
System.out.println("STACK IS EMPTY!");
}
}

0 comments:

Post a Comment