Question

In: Computer Science

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. You may not add any more fields to the class.

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;

   /**
   * Initialize 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
   }
}

Hints:
You will need to store enqueued items on one of the stacks. However, when it comes time to dequeue, those items will be in the wrong order, so use the second stack to reverse the order. Note that once the items are in the second stack, they will come out of the second stack in the correct order and you can still use the first stack to store new items that are enqueued. You should not keep moving the strings back and forth between the two stacks as this will make your solution extremely inefficient. Each string should be inserted into stack1 and most once and into stack2 at most once.
I suggest you start with the very simple sequence: enqueue(“one”), enqueuer(“two”), dequeue(), dequeue(). Of course, the String “one” should come out first followed by the String “two”. Once you have that working, start testing your code with more complex sequences and fixing any use cases you missed in your original attempt at a solution. For example, make sure to at least try the seuquence enqueue(“one”), enqueuer(“two”), dequeue(), enqueue(“three”), dequeue(), dequeue().

Solutions

Expert Solution

//Code for StringQueue using Stacks

//Note: As the Stack is not give, i have implemented it

import java.util.NoSuchElementException;

class Stack
{
String item[] = new String[1000];
int sp;

Stack(){
sp = -1;
}

void push(String itm){
if( isFull() ){
System.out.println("\nStack is Full");
System.exit(0);
}
sp++;
item[sp] = itm;

}

String pop(){
if( isEmpty() ){
System.out.println("\nStack is Empty..");
System.exit(0);
}
String itm = item[sp];
sp--;
return itm;   

}

boolean isEmpty(){
if( sp== -1 )
return true;
return false;
}

boolean isFull(){
if( sp==999)
return true;
return false;

}

int size(){
return( sp+1 );
}

}


public class StringQueue {
//You may NOT add any more fields to this class.
private Stack stack1;
private Stack stack2;

/**
* Initialize an empty queue.
*/
public StringQueue() {
stack1 = new Stack();
stack2 = new Stack();

//TODO
}

/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code false} otherwise
*/
public boolean isEmpty() {
//TODO
if( stack1.isEmpty() && stack2.isEmpty() )
return true;

return false;

}

/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
// TODO
int s1 = stack1.size();
int s2 = stack2.size();

int qsize = s1+2;

return (qsize);
}


/**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(String item) {
// TODO
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 {
// TODO
String itm="";
if( isEmpty() )
{
System.out.println("\nQueue is Empty...");
System.exit(0);
}
if( !stack2.isEmpty() ){
itm = stack2.pop();
return itm;
}

if( !stack1.isEmpty() )
{
while(!stack1.isEmpty()){
itm = stack1.pop();
stack2.push(itm);
}
itm = stack2.pop();
return itm;
  
}
return itm;   
}

public static void main( String args[] ){

StringQueue sq = new StringQueue();
  
sq.enqueue("one");
sq.enqueue("two");

System.out.println(sq.dequeue());
System.out.println(sq.dequeue());

sq.enqueue("one");
sq.enqueue("two");

System.out.println(sq.dequeue());

sq.enqueue("three");
System.out.println(sq.dequeue());
System.out.println(sq.dequeue());

}
}


Related Solutions

Java queue linked list /* * Complete the enqueue(E val) method * Complete the dequeue() method...
Java queue linked list /* * Complete the enqueue(E val) method * Complete the dequeue() method * Complete the peek() method * No other methods/variables should be added/modified */ public class A3Queue {    /*    * Grading:    * Correctly adds an item to the queue - 1pt    */    public void enqueue(E val) {        /*        * Add a node to the list        */    }    /*    * Grading:   ...
Java queue linked list /* * Complete the enqueue(E val) method * Complete the dequeue() method...
Java queue linked list /* * Complete the enqueue(E val) method * Complete the dequeue() method * Complete the peek() method * No other methods/variables should be added/modified */ public class A3Queue {    /*    * Grading:    * Correctly adds an item to the queue - 1pt    */    public void enqueue(E val) {        /*        * Add a node to the list        */    }    /*    * Grading:   ...
Suppose you start with an empty queue and perform the following operations: enqueue 1, enqueue 2,...
Suppose you start with an empty queue and perform the following operations: enqueue 1, enqueue 2, dequeue, enqueue 3, enqueue 4, dequeue, enqueue 5. What are the resultant contents of the queue, from front to back? Group of answer choices 1, 2, 3, 4, 5 1, 3, 5 1, 2, 3 3, 4, 5 Assume you are using the text's array-based queue and have just instantiated a queue of capacity 10. You enqueue 5 elements, dequeue 4 elements, and then...
Discuss the relative efficiency of the enqueue and dequeue operations for an array-based queue implemented with...
Discuss the relative efficiency of the enqueue and dequeue operations for an array-based queue implemented with a fixed-front approach as opposed to a floating-front approach.
java method for dequeue write the “dequeue” method for a queue of type double. If the...
java method for dequeue write the “dequeue” method for a queue of type double. If the queue is empty return 0.0. Make sure to change the links properly ensure that the data structure remains a queue. use the code provided below public class Q04 { public class ListNode//Public for testing purposes { public double data; public ListNode link; public ListNode(double aData, ListNode aLink) { data = aData; link = aLink; } } public ListNode head;//Public for testing purposes public ListNode...
C++ Given Stack Code, Implements Queue. enqueue, dequeue. Modify to function like Queue. Stack #ifndef STACK_H...
C++ Given Stack Code, Implements Queue. enqueue, dequeue. Modify to function like Queue. Stack #ifndef STACK_H #define STACK_H #include "Node.h" template class Stack { private: Node* top; public: // Constructor Stack() { top = nullptr; } void push(Object ab) { if (top != nullptr) { Node* newNode = new Node(ab, *top); top = newNode; } else { Node* newNode = new Node(ab); top = newNode; } } Object pop() { if (top != nullptr) { Node *returnVal = top; top...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class Queue{ public Queue(){ // use the linked list } public void enqueue(int item){ // add item to end of queue } public int dequeue(){ // remove & return item from the front of the queue } public int peek(){ // return item from front of queue without removing it } public boolean isEmpty(){ // return true if the Queue is empty, otherwise false }...
True False The enqueue and dequeue operations in a priority queue take O(lg n) time, while...
True False The enqueue and dequeue operations in a priority queue take O(lg n) time, while linked list and array implementations take O(1) time. A binary heap is a (nearly) complete binary tree. Heaps usually use a linked node structure for implementation. When implementing heaps as arrays, you can leave a blank space at the front. If you do, the parent of a node at index i can be found at index floor(i/2). When implementing heaps as arrays, if you...
Task 3: Implement a queue through circular linked list. Develop enqueue, dequeue, status, isempty and isfull...
Task 3: Implement a queue through circular linked list. Develop enqueue, dequeue, status, isempty and isfull functions. Test your code in main function with 10 elements Note: for each task, you are supposed to create three files as specified in task1, i.e., implementation file, interface file and file containing point of entry. in C++
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting Letter Challenge: Create a function that... Takes in a string as parameter Counts how often each letter appears in the string Returns a dictionary with the counts BONUS: make it so lowercase and uppercase letter count for the same letter
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT