Question

- implement the Stack ADT using array – based approach. Use C++ program language #include "StackArray.h"...

- implement the Stack ADT using array – based approach. Use C++ program language

#include "StackArray.h"

template <typename DataType>
StackArray<DataType>::StackArray(int maxNumber)
{
}

template <typename DataType>
StackArray<DataType>::StackArray(const StackArray& other)
{
}

template <typename DataType>
StackArray<DataType>& StackArray<DataType>::operator=(const StackArray& other)
{
}

template <typename DataType>
StackArray<DataType>::~StackArray()
{
}

template <typename DataType>
void StackArray<DataType>::push(const DataType& newDataItem) throw (logic_error)
{
}

template <typename DataType>
DataType StackArray<DataType>::pop() throw (logic_error)
{

}

template <typename DataType>
void StackArray<DataType>::clear()
{
}

template <typename DataType>
bool StackArray<DataType>::isEmpty() const
{
   return false;
}

template <typename DataType>
bool StackArray<DataType>::isFull() const
{
   return false;
}

template <typename DataType>
void StackArray<DataType>::showStructure() const

// Array implementation. Outputs the data items in a stack. If the
// stack is empty, outputs "Empty stack". This operation is intended
// for testing and debugging purposes only.

{
if( isEmpty() ) {
   cout << "Empty stack." << endl;
}
else {
   int j;
   cout << "Top = " << top << endl;
   for ( j = 0 ; j < maxSize ; j++ )
   cout << j << "\t";
   cout << endl;
   for ( j = 0 ; j <= top ; j++ )
   {
   if( j == top )
   {
   cout << '[' << dataItems[j] << ']'<< "\t"; // Identify top
   }
   else
   {
       cout << dataItems[j] << "\t";
   }
   }
   cout << endl;
}
cout << endl;
}

// Class declaration for the linked implementation of the Stack ADT
//
//--------------------------------------------------------------------

#ifndef STACKARRAY_H
#define STACKARRAY_H

#include <stdexcept>
#include <iostream>

using namespace std;

#include "Stack.h"

template <typename DataType>
class StackArray : public Stack<DataType> {
public:
StackArray(int maxNumber = Stack<DataType>::MAX_STACK_SIZE);
StackArray(const StackArray& other);
StackArray& operator=(const StackArray& other);
~StackArray();

void push(const DataType& newDataItem) throw (logic_error);
DataType pop() throw (logic_error);

void clear();

bool isEmpty() const;
bool isFull() const;

void showStructure() const;

private:
int maxSize;
int top;
DataType* dataItems;
};

#endif       //#ifndef STACKARRAY_H

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

StackArray.cpp


#ifndef STACKARRAY_CPP
#define STACKARRAY_CPP

#include <iostream>

#include "StackArray.h"

//--------------------------------------------------------------------

template <typename DataType>
StackArray<DataType>::StackArray(int maxNumber)

// Creates an empty stack.

    : maxSize(maxNumber), top(-1)
{
    dataItems = new DataType[maxNumber];
}

//--------------------------------------------------------------------

template <typename DataType>
StackArray<DataType>::StackArray(const StackArray& other)

// Copy constructor for linked stack

: maxSize( other.maxSize ), top( other.top )
{
    dataItems = new DataType [ maxSize ];

    // Note: "i<= top" because top is the top item, not the zero-based size.
    for( int i=0; i<=top; i++ )
    {
   dataItems[i] = other.dataItems[i];
    }
}

//--------------------------------------------------------------------

template <typename DataType>
StackArray<DataType>& StackArray<DataType>::operator=(const StackArray& other)

// Overloaded assignment operator for the StackArray class.
// Because this function returns a StackArray object reference,
// it allows chained assignment (e.g., stack1 = stack2 = stack3).

{
    // Self-assignment protection
    if( this != &other ) return *this;

    if( maxSize < other.maxSize ) {
   // This object's array is smaller than the other object's array.
   // Make an equally big array.

   delete[] dataItems;
   dataItems = new DataType [other.maxSize];
    }

    // Now proceed to copy state data over from other object.
    maxSize = other.maxSize;
    top = other.top;
    for( int i=0; i<=top; i++ )
    {

   dataItems[i] = other.dataItems[i];
    }

    return *this;
}

//--------------------------------------------------------------------

template <typename DataType>
StackArray<DataType>::~StackArray()

// Frees the memory used by a stack.

{
    delete[] dataItems;
}

//--------------------------------------------------------------------

template <typename DataType>
void StackArray<DataType>::push(const DataType& newDataItem) throw (logic_error)

// Inserts newDataItem onto the top of a stack.

{
    if (isFull()) {
   throw logic_error("push() while stack full");
    }else
    {
            top++;
            dataItems[top] = newDataItem;
        }
    }

//--------------------------------------------------------------------

template <typename DataType>
DataType StackArray<DataType>::pop() throw (logic_error)

// Removes the topmost data item from a stack and returns it.

{
    if (isEmpty()) {
   throw logic_error("pop() while stack empty");
    }else{
         //ADD YOUR CODE HERE (should require only one line of code)
        top--;
        return dataItems[top +1];
    }
}

//--------------------------------------------------------------------

template <typename DataType>
void StackArray<DataType>::clear()

// Removes all the data items from a stack.

{
    top = -1;
}

//--------------------------------------------------------------------

template <typename DataType>
bool StackArray<DataType>::isEmpty() const

// Returns true if a stack is empty. Otherwise, returns false.

{
    return top == -1;
}

//--------------------------------------------------------------------

template <typename DataType>
bool StackArray<DataType>::isFull() const

// Returns true if a stack is full. Otherwise, returns false.

{
    return top == maxSize - 1;
}

//--------------------------------------------------------------------

template <typename DataType>
void StackArray<DataType>::showStructure() const

// Array implementation. Outputs the data items in a stack. If the
// stack is empty, outputs "Empty stack". This operation is intended
// for testing and debugging purposes only.

{
    if( isEmpty() ) {
   cout << "Empty stack." << endl;
    }
    else {
   int j;
   cout << "top = " << top << endl;
   for ( j = 0 ; j < maxSize ; j++ )
        cout << j << "\t";
   cout << endl;
   for ( j = 0 ; j <= top ; j++ )
   {
        if( j == top )
        {
            cout << '[' << dataItems[j] << ']'<< "\t"; // Identify top
        }
        else
        {
       cout << dataItems[j] << "\t";
        }
   }
   cout << endl;
    }
    cout << endl;
}

#endif       // #ifndef STACKARRAY_CPP


StackArray.h

#ifndef STACKARRAY_H
#define STACKARRAY_H

#include <stdexcept>
#include <iostream>

using namespace std;

#include "Stack.h"

template <typename DataType>
class StackArray : public Stack<DataType> {
public:
    StackArray(int maxNumber = Stack<DataType>::MAX_STACK_SIZE);
    StackArray(const StackArray& other);
    StackArray& operator=(const StackArray& other);
    ~StackArray();

    void push(const DataType& newDataItem) throw (logic_error);
    DataType pop() throw (logic_error);

    void clear();

    bool isEmpty() const;
    bool isFull() const;

    void showStructure() const;

private:
    int maxSize;
    int top;
    DataType* dataItems;
};

#endif       //#ifndef STACKARRAY_H

Stack.h

// for the exception warnings
#pragma warning( disable : 4290 )

#ifndef STACK_H
#define STACK_H

#include <stdexcept>
#include <iostream>

using namespace std;

template <typename DataType>
class Stack {
public:
   static const int MAX_STACK_SIZE = 8;

   virtual ~Stack();

   virtual void push(const DataType& newDataItem) throw (logic_error) = 0;
   virtual DataType pop() throw (logic_error) = 0;

   virtual void clear() = 0;

   virtual bool isEmpty() const = 0;
   virtual bool isFull() const = 0;

   virtual void showStructure() const = 0;
};

template <typename DataType>
Stack<DataType>::~Stack()
// Not worth having a separate class implementation file for the destuctor
{}

#endif       // #ifndef STACK_H

main.cpp


#include <iostream>

using namespace std;


# include "StackArray.cpp"


void print_help()
{
   cout << endl << "Commands:" << endl;
   cout << " H : Help (displays this message)" << endl;
   cout << " +x : Push x" << endl;
   cout << " - : Pop" << endl;
   cout << " C : Clear" << endl;
   cout << " E : Empty stack?" << endl;
   cout << " F : Full stack?" << endl;
   cout << " Q : Quit the test program" << endl;
   cout << endl;
}

template <typename DataType>
void test_stack(Stack<DataType>& testStack)
{
   DataType testDataItem;            // Stack data item
   char cmd;                         // Input command

   print_help();

   do
   {
       testStack.showStructure();                    // Output stack

       cout << endl << "Command: ";                  // Read command
       cin >> cmd;
       if (cmd == '+')
           cin >> testDataItem;

       try {
           switch (cmd)
           {
           case 'H': case 'h':
               print_help();
               break;

           case '+':                                  // push
               cout << "Push " << testDataItem << endl;
               testStack.push(testDataItem);
               break;

           case '-':                                  // pop
               cout << "Popped " << testStack.pop() << endl;
               break;

           case 'C': case 'c':                       // clear
               cout << "Clear the stack" << endl;
               testStack.clear();
               break;

           case 'E': case 'e':                       // isEmpty
               if (testStack.isEmpty())
                   cout << "Stack is empty" << endl;
               else
                   cout << "Stack is NOT empty" << endl;
               break;

           case 'F': case 'f':                       // isFull
               if (testStack.isFull())
                   cout << "Stack is full" << endl;
               else
                   cout << "Stack is NOT full" << endl;
               break;

           case 'Q': case 'q':                   // Quit test program
               break;

           default:                               // Invalid command
               cout << "Inactive or invalid command" << endl;
           }
       }
       catch (logic_error e) {
           cout << "Error: " << e.what() << endl;
       }

   } while (cin && cmd != 'Q' && cmd != 'q');
}

int main() {

   cout << "Testing array implementation" << endl;
   StackArray<char> s1;
   test_stack(s1);

}


Default Term sh-4.2$ main Testing array implementation Browser Commands: H Help (displays this message) +x Push x C Clear F Full stack? -Pop E Empty stack? Q Quit the test program Empty stack. Command: H Commands: H Help (displays this message) +x Push x Pop C Clear E Empty stack? F Full stack? Q Quit the test program Empty stack. Command: tx Push x top0 2 7 https://www.tutorialspoint.com/codingground.htm

Add a comment
Know the answer?
Add Answer to:
- implement the Stack ADT using array – based approach. Use C++ program language #include "StackArray.h"...
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
  • Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use...

    Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use any loop constructs such as while, for and so on. Only use the following stack ADT functions in the recursion: IsEmpty Push Pop Top (note: doesn’t remove anything from the stack). Your program should read 10 integers into a stack from a file named input.txt (outputting them to the screen first) then implement the recursions. Use stacks only, no queues. The program should then...

  • Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp....

    Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp. Add the ouput of the implementation. use recursive functions to traverse the tree - read the implementation notes on using helper functions. Please use C++ programming ////////////////////////////////////////////////////////////// #include "BSTree.h" template <typename DataType, class KeyType> BSTree<DataType, KeyType>::BSTreeNode::BSTreeNode ( const DataType &nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr ) { } template < typename DataType, class KeyType > BSTree<DataType, KeyType>::BSTree () {    root = 0; } template...

  • in c++ please include all of the following " template class, template function, singly linked list,...

    in c++ please include all of the following " template class, template function, singly linked list, the ADT stack, copy constructor, operator overloading, "try catch"and pointers Modify the code named "Stack using a Singly Linked List" to make the ADT Stack that is a template class has the code of the destructor in which each node is directly deleted without using any member function. As each node is deleted, the destructor displays the address of the node that is being...

  • 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...

  • stack.h template class Stack{ public: Stack(int max = 10); ~Stack() {delete [] stack;} bool isEmpty() const...

    stack.h template class Stack{ public: Stack(int max = 10); ~Stack() {delete [] stack;} bool isEmpty() const { return top == -1; } bool isFull() const { return top == MaxStackSize; } T peek() const; void push(const T& x); void pop(); private: int top; int MaxTop; T * stack; } source.cpp What is printed by the following program segment? Stack s; int n; s.push(4); s.push(6); s.push(8); while(!s.isEmpty()) { n = s.peek(); cout << n << ‘ ‘; s.pop(); } cout<< endl;...

  • Review the Stack implementation with Vector, and implement/answer the following methods. Stack One of the principles...

    Review the Stack implementation with Vector, and implement/answer the following methods. Stack One of the principles of good programming is to reuse existing code whenever practical. If you can reuse existing code, you don't need to spend the time to rewrite it. Code used previously has also been debugged, and will likely contain fewer errors. One of the easiest ways to create a container is to leverage an existing data type to build a new abstraction. In this lesson we...

  • template <class T> class Stack { public: /** clear * Method to clear out or empty any items on stack, * put stack back to empty state. * Postcondition: Stack is empty. */ virtual void clear() =...

    template <class T> class Stack { public: /** clear * Method to clear out or empty any items on stack, * put stack back to empty state. * Postcondition: Stack is empty. */ virtual void clear() = 0; /** isEmpty * Function to determine whether the stack is empty. Needed * because it is undefined to pop from empty stack. This * function will not change the state of the stack (const). * * @returns bool true if stack is...

  • I need help fixing my code.   My output should be the following. Hello, world! : false...

    I need help fixing my code.   My output should be the following. Hello, world! : false A dog, a panic in a pagoda : true A dog, a plan, a canal, pagoda : true Aman, a plan, a canal--Panama! : true civic : true If I had a hi-fi : true Do geese see God? : true Madam, I’m Adam. : true Madam, in Eden, I’m Adam. : true Neil, a trap! Sid is part alien! : true Never odd...

  • 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...

  • // thanks for helping // C++ homework // The homework is to complete below in the...

    // thanks for helping // C++ homework // The homework is to complete below in the stack.h : // 1. the copy constructor // 2. the assignment operator // 3. the destructor // 4. Write a test program (mytest.cpp) to test copy and assignment // 5. Verify destructor by running the test program in Valgrind // This is the main.cpp #include <iostream> #include "stack.h" using namespace std; int main() { Stack<int> intStack; cout << "\nPush integers on stack and dump...

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