snippetjavaMinor
Implement a queue using a linked list
Viewed 0 times
implementusinglistlinkedqueue
Problem
Implement a queue using a linked list.
I'm looking for a code review, optimizations and best practices.
I'm looking for a code review, optimizations and best practices.
public class QueueAsLinkedList {
private Node front;
private Node rear;
private int size;
public QueueAsLinkedList() {}
private static class Node {
T item;
Node next;
Node (T item, Node next) {
this.item = item;
this.next = next;
}
}
public void add(T item) {
Node node = new Node(item, null);
if (rear == null) {
rear = node;
front = node;
} else {
rear.next = node;
}
rear = node;
size++;
}
public T remove() {
if (front == null) {
throw new NoSuchElementException();
}
T item = front.item;
front = front.next;
if (front == null) {
rear = null;
}
size--;
return item;
}
public T peek() {
if (front == null) {
throw new NoSuchElementException();
}
return front.item;
}
public int getCount() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public static void main(String[] args) {
QueueAsLinkedList ll = new QueueAsLinkedList();
ll.add(1); ll.add(2); ll.add(3);
while (!ll.isEmpty()) {
System.out.println(ll.remove());
}
}
}Solution
-
There is no point in having the constructor for Node require the 'next' node. It is never part of the constructor, in your code.
-
The default constructor is useless code here. You may as well remove it, it does nothing.
-
the method
-
I prefer when people use just one signal for the system state. In your code, you use
Otherwise the code looks functional, and neat.
There is no point in having the constructor for Node require the 'next' node. It is never part of the constructor, in your code.
-
The default constructor is useless code here. You may as well remove it, it does nothing.
-
the method
getCount should be called size to be conformant with other classes.-
I prefer when people use just one signal for the system state. In your code, you use
size == 0 in some places to determine if the queue is empty, and in other places you use front == nullOtherwise the code looks functional, and neat.
Context
StackExchange Code Review Q#54977, answer score: 5
Revisions (0)
No revisions yet.