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 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 As you are entering strings, they are to be pushed onto a stack.
Ex: If the user enters
one
two
three
the output from the destructor should be:
three deleted!
two deleted!
one deleted!
Empty stack!
Ex: If the user enters the output should be:
Empty stack!
~~~
CIS C
Project: Stack of strings Destructor
Written by:
IDE:
~
#include
#include
using namespace std;
class Stackstr
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:
Stackstr top NULL; length ; Constructor
~Stackstr; Destructor
Stack operations
bool isEmpty;
bool pushstring;
string pop;
string peek;
int getLength;
;
~~~
Member function push: pushes the argument onto the stack.
~
bool Stackstr::pushstring item
StackNode newNode; Pointer to a new node
Allocate a new node and store item there.
newNode new StackNode;
if newNode
return false;
newNodevalue item;
Update links and counter
newNodenext top;
top newNode;
length;
return true;
~~~
Destructor
~
Stackstr::~Stackstr
StackNode currNode;
Position nodePtr at the top of the stack.
currNode top;
Traverse the list deleting each node.
while currNode
cout currNodevalue deleted!" endl;
delete currNode;
currNode NULL;
currNode currNodenext;
cout "Empty stack!" endl;
int main
Stackstr s;
string item;
Write your code here
return ;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
