Question: In Java, Write a class queue that implements the Worklist interface, using a first-in-first-out order. Implement your queue using a linked list. Worklist.java /** *
In Java, Write a class queue that implements the Worklist interface, using a first-in-first-out order. Implement your queue using a linked list.
Worklist.java
/** * An interface for collections of Strings. */ public interface Worklist { /** * Add one String to the worklist. * @param item the String to add */ void add(String item); /** * Test whether there are more elements in the * worklist; that is, test whether more elements have * been added than have been removed. * @return true if there are more elements */ boolean hasMore(); /** * Remove one String from the worklist and return it. * There must be at least one element in the worklist. * @return the String item removed */ String remove(); }// end of Worklist.java
Node.java
/** * A Node is an object that holds a String and a link * to the next Node. It can be used to build linked * lists of Strings. */ public class Node { private String data; // Each node has a String... private Node link; // ...and a link to the next Node /** * Node constructor. * @param theData the String to store in this Node * @param theLink a link to the next Node */ public Node(String theData, Node theLink) { data = theData; link = theLink; } /** * Accessor for the String data stored in this Node. * @return our String item */ public String getData() { return data; } /** * Accessor for the link to the next Node. * @return the next Node */ public Node getLink() { return link; } }// end of node.java
Stack.java
/** * A Stack is an object that holds a collection of * Strings. */ public class Stack implements Worklist { private Node top = null; // The top Node in the stack /** * Push a String on top of this stack. * @param data the String to add */ public void add(String data) { top = new Node(data,top); } /** * Test whether this stack has more elements. * @return true if this stack is not empty */ public boolean hasMore() { return (top != null); } /** * Pop the top String from this stack and return it. * This should be called only if the stack is * not empty. * @return the popped String */ public String remove() { Node n = top; top = n.getLink(); return n.getData(); } }// end of Stack.java
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
