Queues in Java

Def: A squence fo nodes in which we can only access the first item. We add to the last item.


Removing from queue is Dequeue.


Adding to queue is called Enqueue.


Getting first element is called Peek.


Enqueue


Node newNode = new Node(3);
tal.setNExt(newNode);
tail = newNode;

Array Version



Dequeue

returnedElem = head.getITem()
head=head.getNext();


Array Version



Other


You can make a queue object, and you can have an interface that contains all required functions


In the same project, you can import other classes.

import linkedList.Node;// in the format
// package.class;


With Queue


public boolean isEmpty(){
    return head == null; // or tail == null(only one of them, not both, because of '
    // one element/misassigning it)
}

public void enqueue(int x){
    if(!isEmpty()){
        Node n = new Node(x);
        tail.setNext(n);
        tail=n;
    } else{
        head=n;
        tail=n;
    
    }

}

publci int dequeue(){

int res =-1;
if(!isEmpty()){
    res=head.getItem();
    head = head.getNext();
    if(head==null)
        tail=null;// for when you go from 1 -> 0 nodes. 
}

return res;



}

public int peek{
    
}




With peek(array implementation), you can make sure that head is safe, since you already checked last with isEmpty, and because head is before last, the <= 0( so that head is first, and last is second), head always exists