Implementing an LinkedQueue class in java

Problem:

Write a program that implements an LinkedQueue in java.

Output:

Not available.

Solution:

01public class LinkedQueue<E> implements Queue<E> {
02private Node<E> head = new Node<E>(); // dummy node
03private int size;
04 
05public void add(E element) {
06head.prev = head.prev.next = new Node<E>(element, head.prev, head);
07++size;
08}
09 
10public E element() {
11if (size == 0) {
12throw new java.util.EmptyStackException();
13}
14return head.next.element; // front of queue // next <--> prev
15}
16public boolean isEmpty() {
17return (size == 0);
18}
19 
20public E remove() {
21if (size == 0) {
22throw new java.util.EmptyStackException();
23}
24E element = head.next.element; // next <--> prev
25head.next = head.next.next; // next <--> prev
26head.next.prev = head; // next <--> prev
27--size;
28return element;
29}
30public int size() {
31return size;
32}
33private static class Node<E> {
34E element;
35Node<E> prev;
36Node<E> next;
37Node() {
38this.prev = this.next = this;
39}
40Node(E element, Node<E> prev, Node<E> next) {
41this.element = element;
42this.prev = prev;
43this.next = next;
44}
45}
46}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact