Here is a Source code for the Stack using Array In Java.
A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The push operation adds an item to the top of the stack, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation removes an item from the top of the stack, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty stack.
Source Code
/* Stack using array */
import java.io.*;
class MyStack
{
int stack[] = new int[4];
int n=4;
int item;
int top=-1;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
public void push() throws Exception
{
if(top==n-1)
{
System.out.println("Stack is Full !!");
System.out.println("Status of the stack is\n");
for(int i=0;i<=top;i++)
System.out.print(" "+stack[i]);
System.out.print("\n");
}
else
{
System.out.println("Enter the element to be inserted");
item=Integer.parseInt(br.readLine());
stack[++top]=item;
}
}
public int pop() throws Exception
{
if(top==-1)
{
System.out.println("Stack is Empty !!");
//System.exit(-1);
}
else
{
item=stack[top];
top--;
System.out.println(item+" is poped out");
}
return(item);
}
public void traverse() throws Exception
{
int i;
if(top==-1)
{
System.out.println("Stack is Empty !!");
// System.exit(0);
}
else
{
for(i=top;i>=0;i--)
{
System.out.println("Traversed the element "+stack[i]+"\n");
}
}
}
}
class Stack_Menu
{
public void menu() throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
MyStack ms=new MyStack();
while(true)
{
System.out.println("MENU");
System.out.println("1.push\n2.pop\n3.traverse\n4.exit");
System.out.println("\n\nEnter your choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: ms.push();
break;
case 2: ms.pop();
break;
case 3: ms.traverse();
break;
case 4: System.out.println("Good Bye");
System.exit(0);
default: System.out.println("Wrong Choice !!");
}
}
}
}
class Main
{
public static void main(String[] arg)
{
Stack_Menu sm= new Stack_Menu();
try
{
sm.menu();
}
catch(Exception ex)
{
System.out.println("Input-Output Error");
}
}
}
Loading...
|
Comments :
Post a Comment
Enter any comments