Question

In: Computer Science

This is my current code for a question that asks: "Implement the stack methods push(x) and...

This is my current code for a question that asks: "Implement the stack methods push(x) and pop() using two queues". It works well, other than I want it to work for data of type T, not just Int's. (EXCUSE THE INDENTING... CHEGG POSTING DOESNT ALLOW PROPER CODE TO BE UPLOADED... JUST COPY PASTE IT INTO ECLIPSE IDE, HIGHLIGHT ALL CODE, PRESS COMMAND+SHIFT+F AND SHOULD AUTO-FORMAT)

MY QUESTION: How could one modify this code in order to take data of type T, rather than only Int's?

PS: the code must continue to use the data structure provided.... must use the Queue class built... (can't use built-in ArrayList from Java).

HERE IS MY CODE CURRENTLY

//author: Nicolas Wills

package ass1Q1B;

public class StackUsingTwoQueues {

public Queue queue1 = new Queue();

public Queue queue2 = new Queue();

// public int s = queue1.size()+queue2.size(); //dont really use this

// variable... ignore it

public boolean inQueue1 = false; // inQueue1 is true when elements are in queue1. set to false to start means

// first add(x) will add to queue1 first

public void push(int x) { // queue1 holds data when there's an odd number of elements, queue2 holds data

// when even number of elements

if (!inQueue1) { // elements not in queue1, therefore will push to queue1, then transfer queue2

// elements to queue1

queue1.add(x); // add pushed element to previously empty queue1

int queue2StartSize = queue2.size(); // use this variable for "for-loop"... cant put "for(int i=0;

// i

// changes the return value of queue2.size().

for (int i = 0; i < queue2StartSize; i++) {

try {

queue1.add(queue2.remove()); // remove beginning element of queue1, add it to queue2

} catch (NoSuchElementException e) {

}

;

} // end for loop

inQueue1 = true;

} // end else if

else if (inQueue1) { // previous push() added to queue1, therefore add "x" to queue2.

queue2.add(x); // add pushed element to previously empty queue2

int queue1StartSize = queue1.size(); // use this variable for "for-loop"... cant put "for(int i=0;

// i

// change the return value of queue1.size().

for (int i = 0; i < queue1StartSize; i++) {

try {

queue2.add(queue1.remove()); // remove beginning element of queue1, add it to queue2

} catch (NoSuchElementException e) {

}

;

} // end for loop

inQueue1 = false;

} // end else if

}// end push method

// the running time of push O(n+1) time. n for the loop, 1 for the resize()

// operation

public Integer pop() {

Integer x = null; // very sketchy way to get around error

try {

if (inQueue1) {

x = queue1.remove(); // if the elements are currently in queue1, remove first element from queue1

} else {

x = queue2.remove(); // if the elements are currently in queue2, remove first element from queue2

}

} catch (NoSuchElementException e) {

}

;

return x;

}// end pop() method

// the running time of the pop() method is O(1)

public String printArray() {

if (inQueue1) {

return (queue1.stringedArray()); // if the elements are currently in queue1, printArray() will return a

// string version of the contents of queue1

} else

return (queue2.stringedArray()); // if the elements are currently in queue2, printArray() will return a

// string version of the contents of queue2

}

public static void main(String[] args) {

StackUsingTwoQueues myStack = new StackUsingTwoQueues();

// push elements

myStack.push(1);

System.out.println(myStack.printArray());

myStack.push(2);

System.out.println(myStack.printArray());

myStack.push(3);

System.out.println(myStack.printArray());

myStack.push(4);

System.out.println(myStack.printArray());

myStack.push(5);

System.out.println(myStack.printArray());

myStack.push(6);

System.out.println(myStack.printArray());

myStack.push(7);

System.out.println(myStack.printArray());

myStack.push(8);

System.out.println(myStack.printArray());

myStack.push(9);

System.out.println(myStack.printArray());

myStack.push(10);

System.out.println(myStack.printArray());

// pop elements

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

}

}

package ass1Q1B;

//import ass1Q1.illegalOperation;

//import ass1Q1.priorityQ;

public class Queue {

int[] arr = new int[10];

int j=0; // keeps track of index of front of array

int n = 0; //number of elements in array

public int size() {

return n;

}

public boolean add(int x) { // why cant i just return void

if ((n + 1) > arr.length)

resize();

arr[(j + n) % arr.length] = x;

n++;

return true;

}

private void resize() { // only function in queue class that can be private right?

int[] b = new int[(Math.max(1, n * 2))];

for (int k = 0; k < n; k++)

b[k] = arr[(j + k) % arr.length];

arr = b;

j = 0;

}

public int remove() throws NoSuchElementException {

if (n == 0)

throw new NoSuchElementException("cant remove if theres no elements to remove");

int x = arr[j];

j = (j + 1) % arr.length;

n--;

if (arr.length >= 3 * n)

resize();

return x;

}

public String stringedArray() {

String returnString = "";

for(int i=0; i

returnString+= arr[(i+j)%(arr.length)];

}

return returnString;

}

}

Solutions

Expert Solution

// Queue.java

package ass1Q1B;

import java.util.NoSuchElementException;

public class Queue<T> {
       T[] arr = (T[])(new Object[10]); // change it to generic type
      
       int j=0; // keeps track of index of front of array
       int n = 0; //number of elements in array
      
       public int size() {
           return n;
       }
      
       // change the input parameter type to generic
       public boolean add(T x) { // why cant i just return void

           if ((n + 1) > arr.length)
               resize();

           arr[(j + n) % arr.length] = x;
           n++;

           return true;
       }
      
       private void resize() { // only function in queue class that can be private right?

           T[] b = (T[])(new Object[(Math.max(1, n * 2))]);

           for (int k = 0; k < n; k++)
               b[k] = arr[(j + k) % arr.length];

           arr = b;
           j = 0;
       }
      
       // change return data type to generic
       public T remove() throws NoSuchElementException {

           if (n == 0)
               throw new NoSuchElementException("cant remove if theres no elements to remove");

           T x = arr[j];
           j = (j + 1) % arr.length;
           n--;

           if (arr.length >= 3 * n)
               resize();
           return x;

       }
      
       public String stringedArray() {

           String returnString = "";

           for(int i=0; i<n ;i++) {
               returnString+= arr[(i+j)%(arr.length)];
           }

           return returnString;
       }
   }

//end of Queue.java

// StackUsingTwoQueues.java

package ass1Q1B;

import java.util.NoSuchElementException;

public class StackUsingTwoQueues<T> {
  
   // generic queue
   public Queue<T> queue1 = new Queue<>();
   public Queue<T> queue2 = new Queue<>();
  
   // public int s = queue1.size()+queue2.size(); //dont really use this
   // variable... ignore it
  
   public boolean inQueue1 = false; // inQueue1 is true when elements are in queue1. set to false to start means
   // first add(x) will add to queue1 first
  
   // change the data type of the input parameter to generic
   public void push(T x) { // queue1 holds data when there's an odd number of elements, queue2 holds data

       // when even number of elements
       if (!inQueue1) { // elements not in queue1, therefore will push to queue1, then transfer queue2
           // elements to queue1
           queue1.add(x); // add pushed element to previously empty queue1

           int queue2StartSize = queue2.size(); // use this variable for "for-loop"... cant put "for(int i=0;
           // i

           // changes the return value of queue2.size().
           for (int i = 0; i < queue2StartSize; i++) {
               try {
                   queue1.add(queue2.remove()); // remove beginning element of queue1, add it to queue2

               } catch (NoSuchElementException e) {

               }

           } // end for loop

           inQueue1 = true;
       } // end else if
       else if (inQueue1) { // previous push() added to queue1, therefore add "x" to queue2.
           queue2.add(x); // add pushed element to previously empty queue2
           int queue1StartSize = queue1.size(); // use this variable for "for-loop"... cant put "for(int i=0;
           // i
           // change the return value of queue1.size().
           for (int i = 0; i < queue1StartSize; i++) {
               try {
                   queue2.add(queue1.remove()); // remove beginning element of queue1, add it to queue2
               } catch (NoSuchElementException e) {

               }
           } // end for loop

           inQueue1 = false;
       } // end else if

   }// end push method
   // the running time of push O(n+1) time. n for the loop, 1 for the resize()
   // operation
  
   // change the data type of return to generic
   public T pop() {
       T x = null; // very sketchy way to get around error
       try {
           if (inQueue1) {
               x = queue1.remove(); // if the elements are currently in queue1, remove first element from queue1
           } else {
               x = queue2.remove(); // if the elements are currently in queue2, remove first element from queue2
           }
       } catch (NoSuchElementException e) {
       }

       return x;
   }// end pop() method
   // the running time of the pop() method is O(1)

   public String printArray() {
       if (inQueue1) {
           return (queue1.stringedArray()); // if the elements are currently in queue1, printArray() will return a
           // string version of the contents of queue1
       } else
           return (queue2.stringedArray()); // if the elements are currently in queue2, printArray() will return a
       // string version of the contents of queue2
   }
  
   public static void main(String[] args) {
  
       StackUsingTwoQueues<Integer> myStack = new StackUsingTwoQueues<>();

       // push elements

       myStack.push(1);

       System.out.println(myStack.printArray());

       myStack.push(2);

       System.out.println(myStack.printArray());

       myStack.push(3);

       System.out.println(myStack.printArray());

       myStack.push(4);

       System.out.println(myStack.printArray());

       myStack.push(5);

       System.out.println(myStack.printArray());

       myStack.push(6);

       System.out.println(myStack.printArray());

       myStack.push(7);

       System.out.println(myStack.printArray());

       myStack.push(8);

       System.out.println(myStack.printArray());

       myStack.push(9);

       System.out.println(myStack.printArray());

       myStack.push(10);

       System.out.println(myStack.printArray());

       // pop elements

       myStack.pop();
      
       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

       myStack.pop();

       System.out.println(myStack.printArray());

   }

}

//end of StackUsingTwoQueues.java

Output:


Related Solutions

All code should be in Python 3. Implement the Stack Class, using the push, pop, str,...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.
void Stack :: push(float x) {   if (count _______ capacity)                               
void Stack :: push(float x) {   if (count _______ capacity)                                                    // If there is no room for a new value { float* new_A = ______ float[ 2 * ________ ];                     // Create a new array with two-fold capacity for (int i = 0; i < count; ++i)                                   // Copy existing data to new array _______= A[i]; delete[]__________ ;                                                          // Delete old array A = new_A;                                                            // Connect to the new array capacity *= _______ ;                                                    // Update the capacity } A[ ______] =...
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3....
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3. isEmpty 4. PEEK 5. Size */ #include <stdio.h> #define CAPACITY 1000 //Two stacks .. for each stack we need // 1. An Array that can hold capacity of elements // 2. A top initialzied to -1 (signifying that the stak is empty at the start) //NOTE : THESE STACKS ARE OF TYPE CHAR :( ... so you need to FIX IT!!!! to int and...
using C++. edit this code down below so that it will implement stack with linked list...
using C++. edit this code down below so that it will implement stack with linked list contains a default constructor, a copy constructor, and a destructor. #include <iostream> #include <vector> #include <string> #include <stack> #include <limits> using namespace std; class Stack { public: bool isEmpty(); int top(); int pop(); void push(int); void printList(); private: vector<int> elements; }; bool Stack::isEmpty() { return elements.empty(); } int Stack::top() { if(isEmpty()) { throw runtime_error("error: stack is empty"); } return elements.back(); } int Stack::pop() {...
How do you implement stack by using linked list? No code just explain it.
How do you implement stack by using linked list? No code just explain it.
Write a code to implement a python stack class using linked list. use these operations isEmpty...
Write a code to implement a python stack class using linked list. use these operations isEmpty   • push. • pop.   • peek. • size Time and compare the performances ( this is optional but I would appreciate it)
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and...
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and the non-standard min() operation which returns the minimum value stored on the stack. The zip file gives an implementation SlowMinStack that implements these operations so that push(x) and pop() each run in O(1) time, but  min()runs in Θ(n) time. For this question, you should complete the implementation of FastMinStack that implements all three operations in O(1) time per operation. As part of your implementation, you...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
IN JAVA. I have the following code (please also implement the Tester to test the methods...
IN JAVA. I have the following code (please also implement the Tester to test the methods ) And I need to add a method called public int remove() that should remove the first integer of the array and return it at the dame time saving the first integer and bring down all other elements. After it should decrease the size of the array, and after return and save the integer. package ourVector; import java.util.Scanner; public class ourVector { private int[]...
Implement and complement the recursive code to compute the product of two positive integers, x and...
Implement and complement the recursive code to compute the product of two positive integers, x and y, using only addition and/or subtraction. The function will take as its arguments two integers to multiply together ( x x y ) and will return the product. Hint: consider the following: 6 x 1 = 6 6 x 2 = 6 + (6 x 1) 6 x 3 = 6 + (6 x 2) = 6 + [6 + (6 x 1)] =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT