Question

Implement the instance method flip declared as follows (this is a Queue): /** * Reverses ("flips")...

Implement the instance method flip declared as follows (this is a Queue): /** * Reverses ("flips") {@code this}. * * @updates this * @ensures this = rev(#this) */ public void flip(); Rewrite flip, including the contract, so that it is a static method. http://web.cse.ohio-state.edu/software/common/doc/

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Queue can be reversed with the help of another queue.

a.

Required method:

Program:

Sample output:

Code to copy:

import java.util.Iterator;

import components.queue.Queue;

import components.queue.Queue2;

public class QueueWithNewFlip<T> {

    /**

     * Representation of {@code this}.

     */

    private Queue<T> rep;

    QueueWithNewFlip() {

        this.createNewRep();

    }

    private void createNewRep() {

        this.rep = new Queue2<T>();

    }

    public void enqueue(T x) {

        assert x != null : "Violation of: x is not null";

        this.rep.enqueue(x);

    }

    public T dequeue() {

        assert this.rep.length() > 0 : "Violation of: this /= <>";

        return this.rep.dequeue();

    }

    /**

     * Reverses ("flips") {@code this}.

     *

     * @updates this

     * @ensures this = rev(#this)

     */

    public void flip() {

        // Create another queue

        Queue<T> tempq = new Queue2<T>();

        // Repeat until this queue have no elements

        while (this.rep.length() > 0) {

            // remove all elements from this queue one by one, except last

            // element and enqueue into this queue

            for (int i = 0; i < this.rep.length() - 1; i++) {

                this.rep.enqueue(this.rep.dequeue());

            }

            // enqueue the last element into temporary queue

            tempq.enqueue(this.rep.dequeue());

        }

        // again insert all the elements of temporary queue into this queue

        while (tempq.length() > 0) {

            this.rep.enqueue(tempq.dequeue());

        }

        // clear the temporary queue

        tempq.clear();

    }

    public static void main(String args[]) {

        QueueWithNewFlip<Integer> que = new QueueWithNewFlip<Integer>();

        que.enqueue(123);

        que.enqueue(234);

        que.enqueue(345);

        que.enqueue(456);

        // Print the queue before flip

        System.out.println("Before flip: ");

        Iterator<Integer> itrq1 = que.rep.iterator();

        while (itrq1.hasNext()) {

            System.out.println(itrq1.next());

        }

        // Call flip to reverse the queue

        que.flip();

        // Print the queue before flip

        System.out.println("After flip: ");

        Iterator<Integer> itrq2 = que.rep.iterator();

        while (itrq2.hasNext()) {

            System.out.println(itrq2.next());

        }

    }

}

b.

Required modified method:

Program:

Sample output:

Code to copy:

import java.util.Iterator;

import components.queue.Queue;

import components.queue.Queue2;

public class QueueWithNewFlip<T> {

    /**

     * Representation of {@code this}.

     */

    private Queue<T> rep;

    QueueWithNewFlip() {

        this.createNewRep();

    }

    private void createNewRep() {

        this.rep = new Queue2<T>();

    }

    public void enqueue(T x) {

        assert x != null : "Violation of: x is not null";

        this.rep.enqueue(x);

    }

    public T dequeue() {

        assert this.rep.length() > 0 : "Violation of: this /= <>";

        return this.rep.dequeue();

    }

    /**

     * Reverses ("flips") {@code this}.

     *

     * @updates this

     * @ensures this = rev(#this)

     */

    public static <T> void flip(QueueWithNewFlip thiss) {

        // Create another queue

        Queue<T> tempq = new Queue2<T>();

        // Repeat until this queue have no elements

        while (thiss.rep.length() > 0) {

            // remove all elements from this queue one by one, except last

            // element and enqueue into this queue

            for (int i = 0; i < thiss.rep.length() - 1; i++) {

                thiss.rep.enqueue(thiss.rep.dequeue());

            }

            // enqueue the last element into temporary queue

            tempq.enqueue((T) thiss.rep.dequeue());

        }

        // again insert all the elements of temporary queue into this queue

        while (tempq.length() > 0) {

            thiss.rep.enqueue(tempq.dequeue());

        }

        // clear the temporary queue

        tempq.clear();

    }

    public int length() {

        return this.rep.length();

    }

    public static void main(String args[]) {

        QueueWithNewFlip<Integer> que = new QueueWithNewFlip<Integer>();

        que.enqueue(123);

        que.enqueue(234);

        que.enqueue(345);

        que.enqueue(456);

        // Print the queue before flip

        System.out.println("Before flip: ");

        Iterator<Integer> itrq1 = que.rep.iterator();

        while (itrq1.hasNext()) {

            System.out.println(itrq1.next());

        }

        // Call flip to reverse the queue

        que.flip(que);

        // Print the queue before flip

        System.out.println("After flip: ");

        Iterator<Integer> itrq2 = que.rep.iterator();

        while (itrq2.hasNext()) {

            System.out.println(itrq2.next());

        }

    }

}

Add a comment
Know the answer?
Add Answer to:
Implement the instance method flip declared as follows (this is a Queue): /** * Reverses ("flips")...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Implement the static method declared as follows: /** * Divides {@code n} by 2. * *...

    Implement the static method declared as follows: /** * Divides {@code n} by 2. * * @param n *            {@code NaturalNumber} to be divided * @updates n * @ensures 2 * n <= #n < 2 * (n + 1) */ private static void divideBy2(NaturalNumber n) {...} ()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()() Implement the static method declared as follows: /** * Checks whether a {@code String} is a palindrome. * * @param s *            {@code String} to be checked * @return true if {@code...

  • In java Build a QueueInt class for integers that is compatible with the driver code below. The QueueInt should operate in a FIFO (first in, first out) fashion and implement the variables and methods a...

    In java Build a QueueInt class for integers that is compatible with the driver code below. The QueueInt should operate in a FIFO (first in, first out) fashion and implement the variables and methods also listed below: Data Members: Declare and initialize, as needed, the data item(s) you will need to manage a queue of integers. You may only use arrays and primitives for your instance and/or static variables (I,e You can’t use Java defined Queue / Stack / List...

  • In this practical task, you need to implement a class called MyTime, which models a time...

    In this practical task, you need to implement a class called MyTime, which models a time instance. The class must contain three private instance variables: hour, with the domain of values between 0 to 23. minute, with the domain of values between 0 to 59. second, with the domain of values between 0 to 59. For the three variables you are required to perform input validation. The class must provide the following public methods to a user: MyTime() Constructor. Initializes...

  • Define an interface named Shape with a single method named area that calculates the area of...

    Define an interface named Shape with a single method named area that calculates the area of the geometric shape:        public double area(); Next, define a class named Circle that implements Shape. The Circle class should have an instance variable for the radius, a constructor that sets the radius, an accessor and a mutator method for the radius, and an implementation of the area method. Define another class named Rectangle that implements Shape. The Rectangle class should have instance variables...

  • Java Software Originals, Inc., has been hired by Eaton Wright, the "pizza king", to help automate...

    Java Software Originals, Inc., has been hired by Eaton Wright, the "pizza king", to help automate a new chain of pizza delivery stores. SOI's system engineering staff have asked you to implement a prototype for the telephone operator's console. To start the project they have assigned you to implement the following two static methods (the first of which will be used to read files containing menus of pizza sizes and their prices, and pizza toppings and their prices; and the...

  • Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

    Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method: public abstract Product get(String productCode); Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this: IProductDB db...

  • AQueue.java class AQueue implements Queue { private E queueArray[]; // Array holding queue elements private static...

    AQueue.java class AQueue implements Queue { private E queueArray[]; // Array holding queue elements private static final int DEFAULT_SIZE = 10; private int maxSize; // Maximum size of queue private int front; // Index of front element private int rear; // Index of rear element // Constructors @SuppressWarnings("unchecked") // Generic array allocation AQueue(int size) { //BUG #1: maxSize = size maxSize = size+1; // One extra space is allocated rear = 0; front = 1; queueArray = (E[])new Object[maxSize]; //...

  • JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test...

    JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test it is not executing but my stack is working fine, can you fix it please! MyQueue.java Implement a queue using the MyStack.java implementation as your data structure.  In other words, your instance variable to hold the queue items will be a MyStack class. enqueue(String item): inserts item into the queue dequeue(): returns and deletes the first element in the queue isEmpty(): returns true or false...

  • You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement...

    You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement this method return new int[] {}; }    There is a utility method provided for you with the following signature. You may use this method to convert a list of integers into an array. public static int[] convertIntegers(List<Integer> integers) Provided code import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class MatrixSearch { // This method converts a list of integers to an array...

  • Design and implement a class Q that uses Q.java as a code base. The queue ADT...

    Design and implement a class Q that uses Q.java as a code base. The queue ADT must use class LinkedList from Oracle's Java class library and its underlying data structure (i.e. every Q object has-a (contains) class LinkedList object. class Q is not allowed to extend class LinkedList. The methods that are to be implemented are documented in Q.java. Method comment blocks are used to document the functionality of the class Q instance methods. The output of your program must...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT