In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods.
//You may not use the original methods of the stack api to answer.
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.Stack;
public class StringQueue {
//You may NOT add any more fields to this class.
private Stack stack1;
private Stack stack2;
/**
* Initializes an empty queue.
*/
public StringQueue() {
//TODO
}
/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code
false} otherwise
*/
public boolean isEmpty() {
//TODO
}
/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
// TODO
}
/**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(String item) {
// TODO
}
/**
* Removes and returns the item on this queue that was
least recently added.
*
* @return the item on this queue that was least
recently added
* @throws NoSuchElementException if the queue is
empty
*/
public String dequeue() throws NoSuchElementException
{
// TODO
}
}
Solution:
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.Stack;
public class StringQueue {
//You may NOT add any more fields to this class.
private Stack stack1;
private Stack stack2;
/**
* Initializes an empty queue.
*/
public StringQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code false}
otherwise
*/
public boolean isEmpty() {
return stack1.isEmpty();
}
/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
return stack1.size() + stack2.size();
}
/**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(String item) {
if(item == null || item == "" || item == " ")
return;
stack1.push(item);
}
/**
* Removes and returns the item on this queue that was least
recently added.
*
* @return the item on this queue that was least recently
added
* @throws NoSuchElementException if the queue is empty
*/
public String dequeue() throws NoSuchElementException
{
if(stack2.isEmpty())
{
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
}
String popped = stack2.pop();
if(stack1.isEmpty())
{
while(!stack2.isEmpty())
{ stack1.push(stack2.pop());
}
}
return popped;
}
}
Get Answers For Free
Most questions answered within 1 hours.