Answer to Question #239666 in C++ for Shotdown

Question #239666

In a library a librarian is stacking the books using their numeric ids. He may push or pop a book from top and want to know which book ids are currently in the stack. Make a class based menu driven program to take size of stack in 1st line and then either of options – pop, push or stop. If pop or stop option is given no numeric value follows but if push is given a numeric value to be pushed is given.

Sample Input:

5 push 3 push 1 push 9 push 11 pop push 4 push 7 pop stop

Output:

Welcome to stacks!

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Element popped: 11

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Give one of options: pop, push, stop

Element popped: 7

Give one of options: pop, push, stop

Stack elements are:

|4|

---

|9|

---

|1|

---

|3|

---


1
Expert's answer
2021-09-20T16:46:38-0400
#include <iostream>
#include <string>
using namespace std;
class Node{
    public:
    int data;
    Node *next, *prev;
    Node();
    Node(int);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(int data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class Stack{
    Node *head;
    int size, maxsize;


    public:
    Stack(int);
    void push(int);
    int pop();
    void show();
};
Stack::Stack(int x){
    head = NULL;
    size = 0;
    maxsize = x;
}
void Stack::push(int data){
    if(head == NULL){
        head = new Node(data);
        size++;
    }
    else if(size < maxsize){
        Node *temp = new Node(data);
        temp->next = head;
        head = temp;
        size++;
    }
}
int Stack::pop(){
    if(head != NULL){
        Node *temp = head, temp2 = *head;
        cout<<"Element popped: "<<head->data<<endl;
        head = head->next;
        delete temp;
        size--;
        return temp2.data;
    }
    return (int)NULL;
}
void Stack::show(){
    Node* curr = head;
    while(curr != NULL){
        cout<<"|"<<curr->data<<"|"<<endl<<"---\n";
        curr = curr->next;
    }
    cout<<endl;
}
int main(){
    int n; string choice;
    cin>>n;
    Stack s(n);
    cout<<"Welcome to stacks!\n";
    while(choice != "stop"){
        cout<<"Give one of options: pop, push, stop\n";
        cin>>choice;
        if(choice == "push"){
            cin>>n;
            s.push(n);
        }
        else if(choice == "pop"){
            s.pop();
        }
    }
    s.show();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS