Thursday, September 1, 2011

Stack Example in java


//StackExample.java

import java.util.Iterator;
import java.util.Stack;

public class StackExample
{
public static void main(String a[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
s.push(60);
s.push(70);
s.push(80);
s.push(90);

System.out.println("Stack elements are as follows :");
Iterator it1 = s.iterator();
while(it1.hasNext())
{
System.out.println(it1.next());
}

for(int i=1;i<5;i++)
{
System.out.println("popping as LIFO is "+s.pop()+" and now stack elements are as follows:");
Iterator it = s.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

System.out.println("Stack capacity: "+s.capacity());
System.out.println("Stack size: "+s.size());
while(!s.isEmpty())
{
System.out.println("Popping the elements: "+s.pop());
}
System.out.println("\n");
System.out.println("Now the stack size is "+s.size());
System.out.println("Now the stack capacity is "+s.capacity());
}
}

Output =>
Stack elements are as follows :
10
20
30
40
50
60
70
80
90
popping as LIFO is 90 and now stack elements are as follows:
10
20
30
40
50
60
70
80
popping as LIFO is 80 and now stack elements are as follows:
10
20
30
40
50
60
70
popping as LIFO is 70 and now stack elements are as follows:
10
20
30
40
50
60
popping as LIFO is 60 and now stack elements are as follows:
10
20
30
40
50
Stack capacity: 10
Stack size: 5
Popping the elements: 50
Popping the elements: 40
Popping the elements: 30
Popping the elements: 20
Popping the elements: 10


Now the stack size is 0
Now the stack capacity is 10

No comments:

Post a Comment