Question

In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may...

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
   }
}

Homework Answers

Answer #1

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;

}
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(),...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(), and isEmpty(). For this assignment, enqueue() will be implemented in an unusual manner. That is, in the version of enqueue() we will use, if the element being processed is already in the queue then the element will not be enqueued and the equivalent element already in the queue will be placed at the end of the queue. Additionally, you must implement a circular queue....
Code in Java Create a queue class to store integers and implement following methods: 1) void...
Code in Java Create a queue class to store integers and implement following methods: 1) void enqueue(int num): This method will add an integer to the queue (end of the queue). 2) int dequeue(): This method will return the first item in the queue (First In First Out). 3) void display(): This method will display all items in the queue (First item will be displayed first). 4) Boolean isEmpty(): This method will check the queue and if it is empty,...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads in a sequence of strings from standard input using StdIn.readString() , and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 k N , where N is the number of string on standard input. The running time of the program must be linear in the size of...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
(JAVA) Why is my toString method not printing out the last node? It will not print...
(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this. package driver; import exception.StackException; import stack.*; public class StackDriver { public static void main(String[] args) throws Exception { StackInterface<Painting> painting = new LinkedStack <Painting>(); try { System.out.println("Peeking at top of player stack.\n" + painting.peek()); }catch (StackException e) { System.out.println(e); System.out.println("Let's double check if it's empty: " + painting.isEmpty()); }...
Write in Java (Not Javascript) Provide an implementation of priority queue using double-ended doubly linked lists....
Write in Java (Not Javascript) Provide an implementation of priority queue using double-ended doubly linked lists. Recall that double-ended means keeping first and last references and doubly linked feature allows us to go backwards, using a prev reference at each Link. Also, note that the greater the number, the lower the priority. For instance, 2 is of higher priority compared to 5. Specifically, write a class LinkedListPriorityQ which implements the priority queue methods: boolean isEmpty() void enqueue(int item) int dequeue()...
Please answer the following as soon as possible. Thank you. Add the top method in class...
Please answer the following as soon as possible. Thank you. Add the top method in class Stack to the following python code which returns the top item of the stack. Test it. Design top() method using a single queue as an instance variable, and only constant additional local memory within the method bodies. python code: class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self, data): self.q.enqueue(data) def pop(self): for _ in range(self.q.get_size() - 1): dequeued =...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...