here is my LinkedList Queue Implementation , seems like its almost like the linkedlist implementation with little differences mainly in the poll() method, i think that the offer() method is same like the linkedlist method add() , the point is that in the offer() method we are adding the elements to the tail, than we are moving them to the left, but their next is same like the add() method, where we are adding in the head and moving the elements to the right... Is i'm right? I'm glad to hear any suggestations...
import java.util.NoSuchElementException;
public class DynamicQueue {
private class Node {
private Object item;
private Node next;
Node(Object item){
this.item = item;
this.next = null;
}
Node(Object item, Node prevNode){
this.item = item;
prevNode.next = this;
}
}
private Node head;
private Node tail;
private int count;
public DynamicQueue() {
this.head = null;
this.tail = null;
this.count = 0;
}
public int size() {
return count;
}
public void offer(Object item) {
if(tail == null) {
tail = new Node(item);
head = tail;
}else {
Node newNode = new Node(item,tail);
tail = newNode;
}
count++;
}
public void clear() {
head = null;
}
public Object peek() {
if(head == null) {
throw new NoSuchElementException("Overflow Exception");
}else {
return head.item;
}
}
public void poll() {
if(head == null) {
throw new NoSuchElementException("Overflow Exception");
}
Node currentNode = head.next;
head.next = null;
head = currentNode;
count--;
}
public static void main(String[] args) {
DynamicQueue queue = new DynamicQueue();
queue.offer("First");
queue.offer("Second");
queue.offer("Third");
queue.offer("Fourth");
queue.poll();
System.out.println(queue.peek());
queue.poll();
System.out.println(queue.peek());
queue.poll();
System.out.println(queue.peek());
}
}