0% found this document useful (0 votes)
2 views

Stack

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

Stack

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

public interface Stack {

void push(int element);


int pop();
int peek();
boolean isEmpty();
boolean isFull();
}
//

public class FixedSizeStack implements Stack {


private int[] stackData;
private int top;

public FixedSizeStack(int n) {
stackData = new int[n];
top = -1;
}

@Override
public void push(int element) {
if (isFull()) {
throw new IllegalStateException("Stack is full. Cannot push element.");
}
stackData[++top] = element;
}

@Override
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot pop element.");
}
return stackData[top--];
}

@Override
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot peek
element.");
}
return stackData[top];
}

@Override
public boolean isEmpty() {
return top == -1;
}

@Override
public boolean isFull() {
return top == (stackData.length - 1);
}
}

//

public class StackTest {


public static void main(String[] args) {
FixedSizeStack stack = new FixedSizeStack(5);
// Pushing elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);

// Peek the top element


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

// Try pushing onto a full stack (won't be added)


stack.push(60); // Stack is full, so this will not be added

// Popping elements from the stack


System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());

// Check if stack is empty


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

You might also like