Queue

Queue is an abstract data type or a linear data structure very similar to the stack data structure but with one big difference, the first node in the list goes out first the term for this is called “first in first out” or FIFO, and here is an example of a queue data structure in java:


public class Queue {

public static class Node{
private int data;
private Node next;

public Node(int data){
this.data = data;
}

private Node tail;
private Node head;

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

public void push(int value){

Node node = new Node(value);

if(tail != null){
tail.next = node;
}
tail = node;
if(head == null){
head = node;
}

}

public int peek(){
if (head == null)
System.out.print("queue is empty");
return head.data;
}

public int remove(){
int value = head.data;

head = head.next;
if(head == null){
tail = null;
}
return value;
}
}
}

Now let’s test ┬áthe Queue class above:


public class Test {

public static void main(String[] args) {

Stacks newSack = new Stacks();
newSack.push(3);
newSack.push(2);
newSack.push(23);
newSack.push(43);
newSack.push(13);
newSack.push(31);

System.out.println("Before");
System.out.println(newSack.peek());
newSack.pop();
System.out.println("After");

System.out.println(newSack.peek());

}

}

Leave a Reply

Your email address will not be published.