logo CodeStepByStep logo

SortedStack

Define a class called SortedStack using inheritance as described below. Suppose that an existing class named ArrayStack has already been written. An ArrayStack is an implementation of a stack of integers using an array as its internal representation. It has the following implementation:

class ArrayStack {
public:
    ArrayStack();                   // construct empty stack
    ~ArrayStack();                  // free memory

    virtual bool isEmpty() const;   // true if stack has no elements
    virtual int peek() const;       // return top element (error if empty)
    virtual int pop();              // remove/return top element (error if empty)
    virtual void push(int n);       // add to top of stack, resizing if needed

private:
    int* elements;                  // array of stack data (index 0 = bottom)
    int size;                       // number of elements in stack
    int capacity;                   // length of array
};

Define a new class called SortedStack that extends ArrayStack through inheritance. Your class represents a stack of integers that is always stored in sorted non-decreasing order, regardless of the order in which items are pushed onto the stack. Your class should provide the same member functions as the superclass. Your code must work with the existing ArrayStack as shown, unmodified.

For example, if the following elements are added to an empty SortedStack:

42, 27, 39, 3, 55, 81, 11, 9, 0, 72

The following lines show the stack's state before and after adding each element, in bottom-to-top (left-to-right) order:

{}
{42}
{27, 42}
{27, 39, 42}
{3, 27, 39, 42}
{3, 27, 39, 42, 55}
{3, 27, 39, 42, 55, 81}
{3, 11, 27, 39, 42, 55, 81}
{3, 9, 11, 27, 39, 42, 55, 81}
{0, 3, 9, 11, 27, 39, 42, 55, 81}
{0, 3, 9, 11, 27, 39, 42, 55, 72, 81}

You may create ArrayStack objects in your code if it is helpful to do so, but otherwise you should not create any auxiliary data structures (arrays, vectors, queues, maps, sets, strings, etc.) in your code.

Inheritance: Write a C++ class using inheritance.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.