Java Program To Implement Stack Using Oops Concept
class Stack
{
private int stck[] = new int[10];
private int tos;
// Initialize top-of-stack
Stack()
{
tos = -1;
}
// Push an item onto the stack
public void push(int item)
{
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop()
{
if(tos < 0)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class StackOperation
{
public static void main(String args[])
{
Stack firststack = new Stack();
Stack secondstack = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) firststack.push(i);
for(int i=10; i<20; i++) secondstack.push(i);
// pop those numbers off the stack
System.out.println("Stack in firststack:");
for(int i=0; i<10; i++)
System.out.println(firststack.pop());
System.out.println("Stack in secondstack:");
for(int i=0; i<10; i++)
System.out.println(secondstack.pop());
}
}
SAMPLE INPUT AND OUTPUT:
Stack in firststack:
9
8
7
6
5
4
3
2
1
0
Stack in secondstack:
19
18
17
16
15
14
13
12
11
10
Press any key to continue . . .
|