patternjavaMinor
Implementing a queue in Java for a technical interview
Viewed 0 times
javatechnicalinterviewforimplementingqueue
Problem
This code is based off the
Queue implementation in Chapter 3 of Cracking The Coding Interview. I modified the code to make it compile and give me the correct output. I'd appreciate any feedback on code style and correctness, assuming that I write this code in a technical interview.public class Queue {
Node first;
Node last;
public Queue(Node f, Node l) {
first = f;
last = l;
first.next = last;
}
public void enqueue(int data) {
if( first == null ) {
last = new Node(data);
first = last;
} else {
last.next = new Node(data);
last = last.next;
}
}
public int dequeue() {
if (first != null) {
int item = first.data;
first = first.next;
return item;
}
else {
return -1;
}
}
public static void main(String[] args) {
Queue queue = new Queue(new Node(2), new Node(3));
queue.enqueue(4);
queue.enqueue(5);
System.out.println(queue.dequeue() == 2);
System.out.println(queue.dequeue() == 3);
}
public static class Node {
int data;
Node next;
public Node(int d) {
data = d;
}
}
}Solution
You don't have a parameterless constructor which forces each queue to be instantiated with 2 elements. This isn't userfriendly since I might very wel want to construct it first and then add 5 bazillion elements to it.
Your code already allows it though: technically
Right now you only accept integers; perhaps you could make it generic to allow for each type?
Your code doesn't work; executing it will return
Your code already allows it though: technically
first can never be null as it is, yet you check for it. You can add a constructor without a problem.Right now you only accept integers; perhaps you could make it generic to allow for each type?
Node is public; I'd change that to private since the outside world should never use it anyway.Your code doesn't work; executing it will return
2 and -1, not 3. This happens because you don't set the next property of the nodes that are passed in to the Queue(Node, Node) constructor.Context
StackExchange Code Review Q#52556, answer score: 7
Revisions (0)
No revisions yet.