Java

Define class Stack. Data Member : size, top, array of stack. Member method : push, pop, display. Demonstrate the stack class using main method.


import java.util.*;

class Stack {
int size = 10;
int stack[] = new int[size];
int top = -1;

void push(int element) {
if(top >= size-1) {
System.out.println("Stack is overflow.");
}
else {
top++;
stack[top] = element;
}
}

int pop() {
if(top == -1) {
System.out.println("Stack is underflow.");
return -1;
}
else {
top--;
return stack[top+1];
}
}

void display() {
if(top == -1) {
System.out.println("Stack is underflow.");
}
else {
System.out.println(" ----- Elements in stack ----- ");
System.out.println();
for(int i = top; i >= 0; i--) {
System.out.println(" Elements : " + (top-i+1) + " -> " + stack[i]);
}
}
}
}

class StackDemo {
public static void main(String args[]) {
Stack stack = new Stack();

Scanner sc = new Scanner(System.in);

int choice;

System.out.println(" - - - Operation On Stack - - - ");

do {
System.out.println(" 1. Push\n 2. Pop\n 3. Display\n 4. Exit");
System.out.print("Enter your choice : ");
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.print("Enter element in stack : ");
int element = sc.nextInt();
stack.push(element);
break;

case 2:
System.out.println("Popped element is : " + stack.pop());
break;

case 3:
stack.display();
break;

case 4:
break;

default :
System.out.println("Please enter valid choice.");
break;
}
System.out.println();
}while(choice != 4);
}
}

Output :


Post a Comment

0 Comments