The Shaikh Ayaz University Shikarpur
Department of Computer Science & Information
Technology
Data Structure & Algorithms (DSA)
Lab # 4 BS – Computer Science Part-II Date: 06-03-2025
Topic: Stack Implementation
package stackdsa;
class Stack{
private int arr[];
private int top;
private int max_size;
Stack(int size){
arr = new int[size];
max_size = size;
top = -1;
}
public boolean isEmpty(){
return top == -1;
}
public boolean isFull(){
return top == max_size-1;
}
//push
public void push(int x){
if(isFull()){
System.out.println("Stack Overflow! cannot push: " + x);
return;
}
arr[++top] =x;
System.out.println("Pushed: " +x);
}
//pop
public int pop(){
if(isEmpty()){
System.out.println("Stack Undeflow! No Elements to pop");
return -1;
}
return arr[top--];
}
//peek
public int peek(){
if(isEmpty()){
System.out.println("Stack is Empty! No Element at Peek.");
return -1;
}
return arr[top];
//display
public void display(){
if(isEmpty()){
System.out.println("Stack is Empty.");
return;
}
System.out.println("Elements in Stack are: ");
for(int i = 0; i<=top; i++){
System.out.println("Index:" + i + " -> " + arr[i] + " ");
}
System.out.println();
}
}
public class Stackdsa {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Stack stack = new Stack(5);
stack.push(2);
stack.push(5);
stack.display();
}
}
THE END