Queue (Linked List Implementation) and Implement A Stack Using Singly Linked List
Queue (Linked List Implementation) and Implement A Stack Using Singly Linked List
In a Queue data structure, we maintain two pointers, front and rear. The front points the first
item of queue and rear points to last item.
enQueue() This operation adds a new node after rear and moves rear to the next node.
deQueue() This operation removes the front node and moves front to the next node.
Source Code
class QNode {
int key;
QNode next;
// constructor to create a new linked list node
public QNode(int key) {
this.key = key;
this.next = null;
}
}
// A class to represent a queue
// The queue, front stores the front node of LL and rear stores the
// last node of LL
class Queue {
QNode front, rear;
public Queue() {
this.front = this.rear = null;
}
Output:
Dequeued item is 30
Task 2: Implement a stack using singly linked list
All the single linked list operations perform based on Stack operations LIFO and with the help of
that knowledge we are going to implement a stack using single linked list.
using single linked lists so how to implement here it is linked list means what we are storing the
information in the form of nodes and we need to follow the stack rules and we need to
implement using single linked list nodes
Rules of Stack: Last in first out - and all the operations we should perform so with the help of a
top variable only with the help of top variables are how to insert the elements
Push : We will push element to beginning of linked list to demonstrate push behavior
of stack.
Pop : We will remove first element of linked list to demonstrate pop behavior of Stack .
Source Code
public class StackUsingLL {
private Node head; // the first node
public StackUsingLL() {
head = null;
}
//Remove value from beginning of the list for demonstrating behaviour of stack
public int pop() {
if (head == null) {
System.out.println("Linked List is Empty!! Exception occured!!");
return -1;
}
int value = head.value;
head = head.next;
return value;
}
// Add value to the beginning of the list for demonstrating behaviour of stack
public void push(int value) {
Node oldHead = head;
head = new Node();
head.value = value;
head.next = oldHead;
}
Output:
Element removed from LinkedList: 75
Element removed from LinkedList: 60
Element removed from LinkedList: 10
40 80 50 20