1. A function int MaxStack (stackclass S); will return the largest value in an A
ID: 3534809 • Letter: 1
Question
1. A function int MaxStack (stackclass S); will return the largest value in an ADT stack of integers. Write the code for this function. Note: your function will be a client of the ADT, not a part of it, so you must use the ADT operations to access the stack. You can assume the copy constructor for the stack has been implemented.
2. Suppose you are asked to create a new method for the stack class, PopN, defined as follows:
PopN(S, n)
{ Removes from stack S the n number of items that were
most recently added. It is an error if there are
fewer than n items on S. }
To implement this operation, you could either modify the stack directly or use the existing Pop operation. What would be the advantages and disadvantages of each method?
Explanation / Answer
#include<stdio.h>
struct stack
{
int info;
struct stack *next;
};
typedef struct stack node;
class stlink
{
node *start;
public:
stlink()
{
start=NULL;
}
void display(void);
void push(int);
int pop(void);
};
void stlink::push(int term)
{
node *p,*s;
s=start;
if(s==NULL||s!=NULL)
{
p=(node *)malloc(sizeof(node));
p->info=term;
p->next=s;
s=p;
}
start=s;
return;
}
void stlink::display(void)
{
node *temp;
if(start==NULL)
{
cout << endl<<"UNDERFLOEW";
}
temp=start;
while(temp!=NULL)
{
cout << endltemp=temp->next;
}
return;
}
int stlink::pop(void)
{
int term;
if(start==NULL)
{
cout<<"UNDERFLOW";
return(-1);
}
else
{
node *p;
term=start->info;
p=start;
free(start);
start=p->next;
return(term);
}
}
int main()
{
stlink s1;
int ch,temp;
do
{
clrscr();
cout<<"1->Push ";
cout<<"2->Display ";
cout<<"3->Pop ";
cout<<"4->Exit ";
cout<<"Enter your choice:";
cin>>ch;
switch(ch)
{
case'1':
cout<<"Enter the term to push:";
cin>>temp;
s1.push(temp);
break;
case'2':
cout << endl<<"Stack";
s1.display();
getch();
break;
case'3':
temp=s1.pop();
if(temp!=-1)
cout<<"Popped term is " << temp;
getch();
break;
case'4':
cout<<"Exiting";
getch();
break;
default:
cout<<"Invalid choice";
getch();
break;
}
}while(ch!=4);
return(0);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.