Stac
Stac
Stac
Expt: 7
Implementation of Stack
Aim:
Write a java program to implement the stack data structure using
command line arguments.
Algorithm:
Class Stack1:
1: Declare a class named stack1 and declare the data members as stk [] tos; i.
2: Declare a one argument constructor and allocate memory dynamically for
stk.
3: In push function check for stack overflow condition else push an element
into the stack.
4: In pop function check for stack underflow condition else pop an element
out of the stack.
5: Print the stack using the print function.
Class Stac:
Program:
import java.io.*;
class stack1
{
int stk[];
int tos;
int i;
stack1(int size)
{
stk=new int[size];
tos=-1;
}
void print()
{
System.out.println("THE STACK:");
for(i=0;i<=tos;i++)
{
System.out.println(stk[i]);
}
}
int pop()
{
if(tos<0)
{
System.out.println("Stack underflow");
return 0;
}
else
{
return stk[tos--];
}
}
}
class stac
{
public static void main(String args[]) throws IOException
{
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
int x,ch,i,value;
x=Integer.parseInt(args[0]);
stack1 s=new stack1(x);
for(i=1;i<=x;i++)
{
value=Integer.parseInt(args[i]);
s.push(value,x);
}
do
{
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Print");
System.out.println("4. Exit");
System.out.println("Enter the choice");
ch=Integer.parseInt(b.readLine());
switch(ch)
{
case 1:
System.out.println("Enter element:");
value=Integer.parseInt(b.readLine());
s.push(value,x);
s.print();
break;
case 2:
s.pop();
s.print();
break;
case 3:
s.print();
}
}while(ch!=4);
}
}
Output:
41235
1. PUSH
2. POP
3. PRINT
4. EXIT
Enter the choice: 1
Enter the element: 6
Stack full
THE STACK: 1 2 3 5
1. PUSH
2. POP
3. PRINT
4. EXIT
Enter the choice: 2
THE STACK: 1 2 3
1. PUSH
2. POP
3. PRINT
4. EXIT
Enter the choice: 1
Enter the element: 8
THE STACK: 1 2 3 8
1. PUSH
2. POP
3. PRINT
4. EXIT
Enter the choice: 4
Result: