Write a C++ class (or a set of classes) that implements a stack using a linked l
ID: 3870750 • Letter: W
Question
Write a C++ class (or a set of classes) that implements a stack using a linked list. The type of data contained in the stack should be int. The maximum size of the stack is 20. Implement at least the following methods: Constructor and destructor: void push (int number): // pushes an element with the value number into the stack. int pop (): ] // pops an element from the stack. int isEmpty (): // returns 1 if the stack is empty, 0 otherwise. int numOfElements(): // returns the number of elements in the stack. void printElements(): /print out the current stack to the console. A main function: // execute each method of your stack (except the destructor) at least once.Explanation / Answer
Check this fallowing code, desigen as per yor methods just slight bit changes
#include<iostream>
#include<process.h>
using namespace std;
struct Node
{
int data;
Node *next;
}*top=NULL,*p;
Node* newnode(int x)
{
p=new Node;
p->data=x;
p->next=NULL;
return(p);
}
void push(Node *q)
{
if(top==NULL)
top=q;
else
{
q->next=top;
top=q;
}
}
int pop(){
if(top==NULL){
cout<<"Stack is empty!!";
}
else{
cout<<"Deleted element is "<<top->data;
p=top;
top=top->next;
delete(p);
}
}
int isEmpty()
{
Node *q;
q=top;
if(top==NULL){
cout<<"Stack is empty!!";
}
else{
while(q!=NULL)
{
cout<<q->data<<" ";
q=q->next;
}
}
}
int main()
{
int ch,x;
Node *nptr;
while(1)
{
cout<<" 1.Push 2.Pop 3.Display 4.Exit";
cout<<" Enter your choice(1-4):";
cin>>ch;
switch(ch){
case 1: cout<<" Enter data:";
cin>>x;
nptr=newnode(x);
push(nptr);
break;
case 2: pop();
break;
case 3: isEmpty();
break;
case 4: exit(0);
default: cout<<" Wrong choice!!";
}
}
return 0;
}
If needed let me know .. i'll post other methods too
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.