Ila Shukla 22030121093 Assignment 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Name: Ila Shukla PRN: 22030121093 Division C, Sem III, BCA

Stack.java
package MyDataStructure;
public class Stack {
private int maxSize;
private int top;
private int[] stackArray;

public Stack(int size) {


maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

public void push(int value) {


if (top < maxSize - 1) {
stackArray[++top] = value;
System.out.println("Pushed " + value + " to the stack.");
} else {
System.out.println("Stack is full. Cannot push " + value +
".");
}
}

public int pop() {


if (top >= 0) {
int poppedValue = stackArray[top--];
System.out.println("Popped " + poppedValue + " from the
stack.");
return poppedValue;
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1;
}
}

public void printStack() {


if (top >= 0) {
System.out.print("Stack: ");
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
}
Name: Ila Shukla PRN: 22030121093 Division C, Sem III, BCA

Queue.java
package MyDataStructure;
public class Queue {
private int maxSize;
private int front;
private int rear;
private int[] queueArray;

public Queue(int size) {


maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
}

public void insert(int value) {


if (rear < maxSize - 1) {
queueArray[++rear] = value;
System.out.println("Inserted " + value + " into the queue.");
} else {
System.out.println("Queue is full. Cannot insert " + value +
".");
}
}

public int delete() {


if (front <= rear) {
int deletedValue = queueArray[front++];
System.out.println("Deleted " + deletedValue + " from the
queue.");
return deletedValue;
} else {
System.out.println("Queue is empty. Cannot delete.");
return -1;
}
}

public void printQueue() {


if (front <= rear) {
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queueArray[i] + " ");
}
System.out.println();
} else {
System.out.println("Queue is empty.");
}
}
}
Name: Ila Shukla PRN: 22030121093 Division C, Sem III, BCA

DemoDataStructure.java
package DemoPack;

public class DemoDataStructure {


public static void main(String[] args) {
MyDataStructure.Stack stack = new MyDataStructure.Stack(5);
MyDataStructure.Queue queue = new MyDataStructure.Queue(5);

// Demonstrate stack
stack.push(1);
stack.push(2);
stack.push(3);
stack.printStack();
stack.pop();
stack.printStack();

// Demonstrate queue
queue.insert(10);
queue.insert(20);
queue.insert(30);
queue.printQueue();
queue.delete();
queue.printQueue();
}
}

Output-

You might also like