Pages

Friday, October 10, 2025

Queue using LinkedList -most optimized implementation)

 public class QueueB {


    static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }



    static class Queue {
       static Node head = null;
       static Node tail = null;




        public boolean isEmpty() {
            return head == null && tail == null;
        }


        // add
        public void add(int data) {
            Node newNode = new Node(data);
            if(head == null) {
                head = tail = newNode;
                return;
            }
            tail.next = newNode;
            tail = newNode;
        }

        // remove
        public int remove() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }

            int front = head.data;
            // last element deleted
            if (tail == head) {
               tail = head = null;
            } else {
                head = head.next;
            }
            return front;
        }

        // peek
        public int peek() {
            if (isEmpty()) {
                System.out.println("Queue is empty");
                return -1;
            }

            return head.data;
        }
    }

    public static void main(String args[]) {
        Queue q = new Queue();
        q.add(1);
        q.add(2);
        q.add(3);
        // adding condition that works like a circular queue
        System.out.println(q.remove()); // prints 1
        q.add(4);
        System.out.println(q.remove()); // prints 2
        q.add(5);
        // queue now contains 3,4,5 in order

        while (!q.isEmpty()) {
            System.out.println(q.peek());
            q.remove();
        }
    }
}
output: 1
2
3
4
5

No comments:

Post a Comment

Encode and Decode Strings - NeetCode.IO Solution by me + gemini pro 3.0 explained

  class Solution {         // encode: List of Strings -> String     public String encode ( List < String > strs) {         Stri...