Add On
Add On
Scanner;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
void dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty.");
} else {
System.out.println("Dequeued: " + front.data);
front = front.next;
if (front == null) {
rear = null;
}
}
}
void displayQueue() {
if (isEmpty()) {
System.out.println("Queue is empty.");
} else {
Node temp = front;
System.out.print("Queue: ");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
Output:
Algorithm :
1. Start.
2. Define a class Node with instance variables data and next.
3. Define a class QueueLinkedList with instance variables front and rear.
4. Implement the isEmpty() method to check if the queue is empty.
5. Define the enqueue() method to add an element to the queue.
6. Define the dequeue() method to remove an element from the queue.
7. Implement the displayQueue() method to display the elements of the queue.
8. In main(), create a queue.
9. Perform enqueue and dequeue operations.
10. Display the queue after operations.
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
void pop() {
if (isEmpty()) {
System.out.println("Stack is empty.");
} else {
System.out.println("Popped: " + top.data);
top = top.next;
}
}
void displayStack() {
if (isEmpty()) {
System.out.println("Stack is empty.");
} else {
Node temp = top;
System.out.print("Stack: ");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
Output:
Algorithm :
1. Start.
2. Define a class Node with instance variables data and next.
3. Define a class StackLinkedList with an instance variable top.
4. Implement the isEmpty() method to check if the stack is empty.
5. Define the push() method to add an element to the stack.
6. Define the pop() method to remove an element from the stack.
7. Implement the displayStack() method to display the elements of the stack.
8. In main(), create a stack.
9. Perform push and pop operations.
10. Display the stack after operations.