This is an exercise in queues. You are to implement a linked queue. Make sure yo
ID: 3626885 • Letter: T
Question
This is an exercise in queues. You are to implement a linked queue. Make sure you implement all operations in the interface, including the ToString.You are to write a driver to declare a queue of String types. It should read in strings from a keyboard. These will either be commands to the program, or strings to be enqueued the queue. Commands will start with the character '@' and are as follows.
@ dequeue remove and print the first item. If the queue is empty, print an error message.
@ first print the first item. If the queue is empty, print an error message.
@print print the items in the queue. Use the toString method to do this. If the queue is empty, you should just print the word "empty"
Explanation / Answer
public class Node<T>
{
private T value;
private Node<T> next;
public Node(T value)
{
this(null, value);
}
public Node(Node<T> next, T value)
{
this.next = next;
this.value = value;
}
public Node<T> getNext()
{
return next;
}
public void setNext(Node<T> next)
{
this.next = next;
}
public T getValue()
{
return value;
}
}
public class LinkedQueue<T>
{
private Node<T> first;
private Node<T> last;
public LinkedQueue(){}
public void enqueue(T value)
{
// case head is null
if(first == null)
{
first = new Node<T>(value);
last = first;
}
// otherwise add to back
else
{
last.setNext(new Node<T>(value));
last = last.getNext();
}
}
public T dequeue()
{
// case head is null
if(first == null)
{
return null;
}
// otherwise if head is not null, remove head
else
{
T output = first.getValue();
first = first.getNext();
if(first == null)
last = null;
return output;
}
}
public T peek()
{
if(first == null)
return null;
else
return first.getValue();
}
public boolean isEmpty()
{
return first == null;
}
public String toString()
{
String output = "[";
Node<T> curr = first;
while(curr != null)
{
output += curr.getValue().toString()+", ";
curr = curr.getNext();
}
if(output.length() > 1)
output = output.substring(0, output.length()-2);
output += "]";
return output;
}
}
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
LinkedQueue<String> test = new LinkedQueue<String>();
// read from
while(true)
{
System.out.print("> ");
String word = kb.next();
// if command
if(word.charAt(0) == '@')
{
if(word.equals("@dequeue"))
{
if(test.isEmpty())
System.out.println("empty");
else
System.out.println(test.dequeue());
}
else if(word.equals("@first"))
{
if(test.isEmpty())
System.out.println("empty");
else
System.out.println(test.peek());
}
else if(word.equals("@print"))
{
if(test.isEmpty())
System.out.println("empty");
else
System.out.println(test.toString());
}
}
// otherwise enqueue
else
{
test.enqueue(word);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.