To implement a queue using Linkedlist we can use double ended Linkedlist.
A double ended Linkedlist has first and last node pointer. So we can insert item at last to implement enqueue operation using last pointer. To implement dequeue operation we can remove item from the first using first node.
Below is the implementation:
class Link:
public class Link {
public long data;
public Link next;
public Link(long data) {
this.data = data;
}
public void displayLink() {
System.out.println("data :"+ data);
}
}
class FirstLastList:
public class FirstLastList {
private Link first;
private Link last;
public FirstLastList() {
first = null;
last = null;
}
public boolean isEmpty() {
return first == null;
}
public void insertLast(long data) {
Link newLink = new Link(data);
if (isEmpty()) {
first = newLink;
} else {
last.next = newLink;
}
last = newLink;
}
public long removeFirst() {
Link temp = first;
first = first.next;
return temp.data;
}
public void display() {
Link current = first;
while (current != null) {
System.out.print(current.data + "-->");
current = current.next;
}
}
}
class LinkQueue:
public class LinkQueue {
private FirstLastList firstLastList;
public LinkQueue() {
this.firstLastList = new FirstLastList();
}
public void enqueue(long data) {
firstLastList.insertLast(data);
}
public void dequeue() {
firstLastList.removeFirst();
}
public void displayQueue() {
firstLastList.display();
}
}
class MainApp:
public class MainApp {
public static void main(String[] args) {
LinkQueue queue = new LinkQueue();
queue.displayQueue();
System.out.println("after enqueue new item");
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.displayQueue();
System.out.println("\n");
queue.dequeue();
System.out.println("after dequeue item");
queue.displayQueue();
}
}