In: Electrical Engineering
Solve
this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. · int isEmpty(); // returns 1 if the stack is empty, 0 otherwise. 5 pts. · int numElements(); // returns the number of elements in the stack. 5 pts. · void print Elements(); // print out the current stack to the console. 5 pts. · A main function; // execute each method of your stack (except the destructor) at least once without asking input from the users.
Hello,
Please find the answer
attached below. If the answer has helped you please give a thumbs
up rating. Thank you and have a nice day!
// Creating a NODE Structure
struct node
{
int data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *top;
public:
stack() // constructor
{
top=NULL;
}
~stack() // destructor
{
cout << " Destructor invoked";
}
void push(double value); // to insert an element
double pop(); // to pop an element
void print Elements(); // to show the stack
int isEmpty(); //returns 1 if the stack is empty, 0 otherwise
int numElements(); // returns the number of elements in the stack
};
// PUSH Operation
void stack::push(double value)
{
struct node *ptr;
ptr=new node;
ptr->data=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
cout<<"\nNew item inserted";
}
// POP Operation
double stack::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"\nempty stack";
}
temp=top;
top=top->next;
return temp;
}
int stack::isEmpty()
{
struct node *temp;
if(top==NULL)
return 1;
else
return 0;
}
int stack::numElements()
{
struct node *ptr1=top;
int p;
while(ptr1!=NULL)
{
p++;
ptr1=ptr1->next;
}
return p;
}
// Show all elemnts in stack
void stack::printElements()
{
struct node *ptr1=top;
cout<<"\nThe stack is\n";
while(ptr1!=NULL)
{
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
}
cout<<"NULL\n";
}
// Main function
int main()
{
stack sll;
cout<<"\n-----------------------------------------------------------";
cout<<"\n\t\tSTACK USING LINKED LIST\n\n";
sll.push(23);
sll.pop();
sll.isEmpty();
sll.numElements();
s.printElements();
return 0;
}