Skip to content

Instantly share code, notes, and snippets.

@Rohit-554
Created March 24, 2023 10:43
Show Gist options
  • Select an option

  • Save Rohit-554/a69a788aef0abd0734cb2bbfc2a777d2 to your computer and use it in GitHub Desktop.

Select an option

Save Rohit-554/a69a788aef0abd0734cb2bbfc2a777d2 to your computer and use it in GitHub Desktop.
Queue Implementation using Linked List
public class queue {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
Node head = null;
Node tail = null;
public boolean isEmpty() {
return head == null && tail == null;
}
public void add(int data) {
Node newNode = new Node(data);
if(isEmpty()) {
tail = head = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public int remove() {
if(isEmpty()) {
System.out.println("empty queue");
return -1;
}
int front = head.data;
//single node
if(head == tail) {
tail = null;
}
head = head.next;
return front;
}
public int peek() {
if(isEmpty()) {
System.out.println("empty queue");
return -1;
}
return head.data;
}
public static void main(String[] args) {
queue q = new queue();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
//here we get the referernce of the current node
Node current = q.head;
while(current != null) {
//current is iterating over each node until it gets last one i.e, null
System.out.println(current.data); //printing the values
current = current.next; //going to the next node
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment