0% found this document useful (0 votes)
11 views4 pages

Exp1 Java

The document describes a Java program that implements both a stack and queue data structure. The program defines a StackAndQueue class with arrays and indexes to track both structures within the same class. The class contains push(), pop(), enqueue(), and dequeue() methods to add and remove elements from each structure, and outputs the results. The main method demonstrates using each structure.

Uploaded by

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

Exp1 Java

The document describes a Java program that implements both a stack and queue data structure. The program defines a StackAndQueue class with arrays and indexes to track both structures within the same class. The class contains push(), pop(), enqueue(), and dequeue() methods to add and remove elements from each structure, and outputs the results. The main method demonstrates using each structure.

Uploaded by

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

PROGRAM-1

AIM: Write a java program to implement stack and queue concept.

ALGORITHM:
CODE:
public class StackAndQueue {

private int[] stackArray;


private int[] queueArray;
private int top;
private int front;
private int rear;
private int maxSize;

public StackAndQueue(int size) {


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

public void push(int data) {


if (top < maxSize - 1) {
stackArray[++top] = data;
System.out.println(data + " pushed into stack");
} else {
System.out.println("Stack Overflow");
}
}

public int pop() {


if (top >= 0) {
int popped = stackArray[top--];
System.out.println(popped + " popped from stack");
return popped;
} else {
System.out.println("Stack Underflow");
return -1;
}
}

public void enqueue(int data) {


if (rear < maxSize - 1) {
queueArray[++rear] = data;
System.out.println(data + " enqueued into queue");
} else {
System.out.println("Queue Overflow");
}
}

public int dequeue() {


if (front <= rear) {
int dequeued = queueArray[front++];
System.out.println(dequeued + " dequeued from queue");
return dequeued;
} else {
System.out.println("Queue Underflow");
return -1;
}
}

public static void main(String[] args) {


StackAndQueue sq = new StackAndQueue(5);
sq.push(10);
sq.push(20);
sq.push(30);
sq.pop();
sq.enqueue(40);
sq.enqueue(50);
sq.enqueue(60);
sq.dequeue();
sq.dequeue();
sq.dequeue();
sq.dequeue();
}
}
OUTPUT :

You might also like