Write a fulll program in which the user repeatedly enters one of 3 things: 1) th
ID: 3726908 • Letter: W
Question
Write a fulll program in which the user repeatedly enters one of 3 things: 1) the word ADD followed by an integer, 2) the word UNDO, or 3) the word DISPLAY. Starting at 0, each time a number is added, it should be added to a running total. Each UNDO, on the other hand, should "undo" the most recently added number from the running total. DISPLAY should simply print the current sum to the screen. Use a stack class as a linked list. Here is an example input from the user, along with what should be displayed:
ADD 10
ADD 5
ADD 20
ADD 30
DISPLAY (this should print 65)
ADD 5
UNDO
UNDO
UNDO
ADD 2
ADD 3
DISPLAY (this should display 20)
Explanation / Answer
Hi,
Please find the program for your operations as you have mentione and please let me know if you have any changes/modification.:
#include<iostream>
using namespace std;
// Main Node using struct
struct node
{
int data;
struct node *next;
};
// Defention of Class stack
class stack
{
struct node *top;
public:
stack()
{
top=NULL;
}
void add(int);
void clear_last_value();
void sum_of_values();
};
// ADD operation
void stack::add(int input_value)
{
struct node *ptr;
ptr=new node;
ptr->data=input_value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
}
// UNDO operation
void stack::clear_last_value()
{
struct node *temp;
if(top==NULL)
{
cout<<"Empty queue!!!";
}
temp=top;
top=top->next;
delete temp;
}
// DISPLAY operation
void stack::sum_of_values()
{
struct node *ptr1=top;
int sum= 0;
while(ptr1!=NULL)
{
sum += ptr1->data;
ptr1=ptr1->next;
}
cout<< sum << ' ';
}
int main()
{
stack s;
int choice,lenth,input_value;
string str,choice_str;
cout<<" Enter your operations like (ADD|DISPLAY|UNDO) : ";
while(1)
{
cin>>str;
string choice_str = str.substr(0, 3);
if (choice_str == "ADD")
{
cin>>input_value;
s.add(input_value);
}
else if (choice_str == "UND")
{
s.clear_last_value();
}
else if (choice_str == "DIS")
{
s.sum_of_values();
}
else
{
exit(0);
}
}
return 0;
}
Sample Output:
Enter your operations like (ADD|DISPLAY|UNDO) :
ADD
10
ADD
5
ADD
20
ADD
30
DISPLAY
65
ADD
5
UNDO
UNDO
UNDO
DISPLAY
15
ADD
2
ADD
3
DISPLAY
20
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.