Stac

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 4

Date:

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:

1: Declare a class stac and implement the main function in it.


2: Create an object b for the BufferedReader class to get interactive inputs.
3: Create an object s for the stack1 class.
4: In a switch case call all the function according to the choice.

Program:

import java.io.*;
class stack1
{
int stk[];
int tos;
int i;
stack1(int size)
{
stk=new int[size];
tos=-1;
}

void push (int item, int x)


{
if(tos==(x-1))
System.out.println("Stack full");
else
{
stk[++tos]=item;
}
}

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:

Thus a java program is written to implement stack data structure using


command line arguments.

You might also like