Question

Develop a generic stack ADT class by once again implementing the StackInterface.java and use Queue object...

Develop a generic stack ADT class by once again implementing the StackInterface.java and use Queue object as underlying ADT(implement stack using queue)

Include two constructors: one that sets the capacity at 100 elements, and the other that allows the application level to provide a capacity value as an actual parameter with the constructor call.

Also include a toString method.

StackInterface :

package interfaces;

public interface StackInterface<E> {

void push(E element); // add an element to the stack - always at the "top"

E pop(); // remove and return the top of the stack

E peek(); // return the top of the stack ... without removing

boolean isEmpty();

boolean isFull();

}

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

Hi, I have answered this question before. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

EDIT: included Queue implementation (using two stacks) also, and a Test class for testing.

// Stack.java

package adts;

import interfaces.StackInterface;

public class Stack<T> implements StackInterface<T> {

      // an ArrayQueue object as underlying structure

      private ArrayQueue<T> queStack;

      // default constructor, initializes capacity to 100

      public Stack() {

            queStack = new ArrayQueue<T>(100);

      }

      // constructor taking initial capacity

      public Stack(int capacity) {

            queStack = new ArrayQueue<T>(capacity);

      }

      @Override

      public void push(T element) {

            // finding current size

            int size = queStack.numElements;

            // adding at the end

            queStack.enqueue(element);

            // now removing all elements upto the last element and adding to the

            // end, making last element first

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

                  queStack.enqueue(queStack.dequeue());

            }

      }

      @Override

      public T pop() {

            // just removing and returning last element of queue (top element of

            // stack)

            return queStack.dequeue();

      }

      @Override

      public T peek() {

            if (isEmpty())

                  return null;

            // since there is no front() method defined in ArrayQueue, we have to

            // return the element at queStack.front index

            return queStack.queue[queStack.front];

      }

      @Override

      public boolean isEmpty() {

            return queStack.isEmpty();

      }

      @Override

      public boolean isFull() {

            return queStack.isFull();

      }

      @Override

      public String toString() {

            String stackString = "Stack: (top)[";

            int size = queStack.numElements;

            //appending all values to a String

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

                  //removing last element from queue (top of stack)

                  T item = queStack.dequeue();

                  stackString += item;

                  //adding to end

                  queStack.enqueue(item);

                  if (i != size - 1) {

                        stackString += ", ";

                  }

            }

            stackString += "]";

            return stackString;

      }

}

// Queue.java

package adts;

import interfaces.QueueInterface;

public class Queue<T> implements QueueInterface<T> {

      // two ArrayStack objects as underlying datastructures

      private ArrayStack<T> stk1;

      private ArrayStack<T> stk2;

      // default constructor

      public Queue() {

            stk1 = new ArrayStack<T>(100);

            stk2 = new ArrayStack<T>(100);

      }

      // constructor taking capacity

      public Queue(int capacity) {

            stk1 = new ArrayStack<T>(capacity);

            stk2 = new ArrayStack<T>(capacity);

      }

      @Override

      public void enqueue(T element) {

            // removing all values from stk1 and adding to stk2

            while (!stk1.isEmpty()) {

                  stk2.push(stk1.pop());

            }

            // adding new element to stk1

            stk1.push(element);

            // removing all elements from stk2 to stk1

            while (!stk2.isEmpty()) {

                  stk1.push(stk2.pop());

            }

      }

      @Override

      public T dequeue() {

            if (isEmpty())

                  return null;

            // just removing and returning the top element of stk1, which is the

            // front element of this queue

            return stk1.pop();

      }

      @Override

      public boolean isEmpty() {

            // queue is empty if stk1 is empty

            return stk1.isEmpty();

      }

      @Override

      public boolean isFull() {

            // queue is full if stk1 is full

            return stk1.isFull();

      }

      @Override

      public String toString() {

            String queStr = "Queue: (front)[";

            // looping until stk1 is empty

            while (!stk1.isEmpty()) {

                  // popping and appending each value to string

                  T item = stk1.pop();

                  queStr += item;

                  if (!stk1.isEmpty()) {

                        queStr += ", ";

                  }

                  // adding to stk2

                  stk2.push(item);

            }

            // now removing all elements from stk2 to stk1

            while (!stk2.isEmpty()) {

                  stk1.push(stk2.pop());

            }

            queStr += "]";

            return queStr;

      }

}

// Test.java

package adts;

public class Test {

      public static void main(String[] args) {

            //testing both new classes

            System.out.println("Testing Stack\n");

            Stack<Integer> stk = new Stack<Integer>();

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

                  stk.push(i);

            }

            System.out.println(stk);

            while (!stk.isEmpty()) {

                  System.out.println(stk.pop() + " is popped");

            }

            System.out.println("\n\nTesting Queue\n");

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

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

                  que.enqueue(i);

            }

            System.out.println(que);

            while (!que.isEmpty()) {

                  System.out.println(que.dequeue() + " is dequed");

            }

      }

}

/*OUTPUT*/

Testing Stack

Stack: (top)[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

9 is popped

8 is popped

7 is popped

6 is popped

5 is popped

4 is popped

3 is popped

2 is popped

1 is popped

0 is popped

Testing Queue

Queue: (front)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

0 is dequed

1 is dequed

2 is dequed

3 is dequed

4 is dequed

5 is dequed

6 is dequed

7 is dequed

8 is dequed

9 is dequed

Add a comment
Know the answer?
Add Answer to:
Develop a generic stack ADT class by once again implementing the StackInterface.java and use Queue object...
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
  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top...

    QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top entry at the end of the array" at array index N-1 where the array is currently allocated to hold up to N entries. MAKE SURE YOU IMPLEMENT the functions:  bool isEmpty() const; bool push(const ItemType& newEntry); bool pop(); in ArrayStackP4.cpp //FILE StackInterface.h #ifndef STACK_INTERFACE_ #define STACK_INTERFACE_ template<class ItemType> class StackInterface { public:    /** Sees whether this stack is empty.    @return True if the...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • JUnit5 JAVA. Need help to make a unit test of my GenericStack.java code below. Feel free...

    JUnit5 JAVA. Need help to make a unit test of my GenericStack.java code below. Feel free to change the code below to fit the task better. thanks :) Assigment Create a new version of GenericStack (Have started on the code below) that uses an array instead of an ArrayList (this version should also be generic). Be sure to check the size of the array before adding a new item; - if the array becomes full, double the size of the...

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