KEMBAR78
Stack | PDF
0% found this document useful (0 votes)
9 views3 pages

Stack

The document contains a Java implementation of a Stack data structure with methods for pushing, popping, checking the top element, and verifying if the stack is empty. It includes error handling for stack overflow and underflow conditions. The main class demonstrates the usage of the Stack class by performing a series of push and pop operations.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Stack

The document contains a Java implementation of a Stack data structure with methods for pushing, popping, checking the top element, and verifying if the stack is empty. It includes error handling for stack overflow and underflow conditions. The main class demonstrates the usage of the Stack class by performing a series of push and pop operations.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

import java.util.

*;

class Stack {

int maxSize;

int[] stackArray;

int top;

Stack(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1;

void push(int value) {

if (top == maxSize - 1) {

System.out.println("Stack overflow");

return;

stackArray[++top] = value;

System.out.println(value + " pushed into the stack");

int pop() {

if (top == -1) {

System.out.println("Stack underflow");

return -1;

int popped = stackArray[top--];


System.out.println(popped + " popped from the stack");

return popped;

int top() {

if (top == -1) {

System.out.println("Stack is empty");

return -1;

return stackArray[top];

boolean isEmpty() {

return top == -1;

public class Main {

public static void main(String[] args) {

Stack stack = new Stack(5);

stack.push(10);

stack.push(20);

stack.push(30);

System.out.println("Top element: " + stack.top());

stack.pop();
stack.pop();

stack.pop();

stack.pop();

System.out.println("Is stack empty? " + stack.isEmpty());

You might also like