Question: The program you wrote in Stacks 1 is incomplete. Without a destructor it creates a memory leak. A destructor has been defined in this program

The program you wrote in Stacks 1 is incomplete. Without a destructor it creates a memory leak. A destructor has been defined in this program but it is incorrect. To visualize how the destructor works, a cout statement has been added. Fix the errors, including the cout statement, to display the value in each node of the stack before releasing the memory.
Write a loop in main() to enter an unknown number of strings, one string per line. The loop stops when you enter 0. As you are entering strings, they are to be pushed onto a stack.
Ex.: If the user enters
one
two
three
0
the output (from the destructor) should be:
three - deleted!
two - deleted!
one - deleted!
Empty stack!
Ex.: If the user enters 0 the output should be:
Empty stack!
/**~*~*~*
CIS 22C
Project: Stack of strings (Destructor)
Written by:
IDE:
*~*/
#include
#include
using namespace std;
class Stack_str
{
private:
// Structure for the stack nodes
struct StackNode {
string value; // Value in the node
StackNode *next; // Pointer to next node
};
StackNode *top; // Pointer to the stack top
int length; // Number of nodes
public:
Stack_str(){ top = NULL; length =0; }//Constructor
~Stack_str(); // Destructor
// Stack operations
// bool isEmpty();
bool push(string);
// string pop();
// string peek();
// int getLength();
};
/**~*~*~*
Member function push: pushes the argument onto the stack.
*~**/
bool Stack_str::push(string item)
{
StackNode *newNode; // Pointer to a new node
// Allocate a new node and store item there.
newNode = new StackNode;
if (!newNode)
return false;
newNode->value = item;
// Update links and counter
newNode->next = top;
top = newNode;
length++;
return true;
}
/**~*~*~*
Destructor
*~**/
Stack_str::~Stack_str()
{
StackNode *currNode;
// Position nodePtr at the top of the stack.
currNode = top;
// Traverse the list deleting each node.
while (currNode)
{
cout << currNode->value <<"- deleted!" << endl;
delete currNode;
currNode = NULL;
currNode = currNode->next;
}
cout << "Empty stack!" << endl;
}
int main(){
Stack_str s;
string item;
/* Write your code here */
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!