Question: #1 C++, when the stack is empty and I chose to pop more than 1 it prints out the Stack is empty more than one.
#1 C++, when the stack is empty and I chose to pop more than 1 it prints out the Stack is empty more than one. I want to display it only once. Please edit my code.
Code: #include
class Node { public: int data; Node* next;
};
class Stack { public: Node* top; Stack() { top = NULL; }
void push(int data) { Node* node = new Node(); node -> data = data; node -> next = top; top = node; }
void pop() { if(top==NULL) { cout << "Stack is empty!" << endl; } else { Node* temp = top; top = top -> next; delete temp; } }
void display() { if(top==NULL) { cout << "Stack is empty!" << endl; } else { Node* temp = top; while(temp!=NULL) { cout << temp -> data << " "; temp = temp -> next; } cout << endl; } } };
int main() { Stack stack;
int choice, data, no;
while(1) { cout << "1. Push to stack" << endl; cout << "2. Pop from stack" << endl; cout << "3. Display stack" << endl; cout << "4. Exit" << endl; cout << "Enter your choice: "; cin >> choice;
if(choice == 1) { cout << "Enter data to push: "; cin >> data; stack.push(data); } else if(choice == 2) { cout << "How many items to pop: "; cin >> no;
for (; no--; stack.pop()); } else if(choice == 3) { stack.display(); } else if(choice == 4) { break; } else { cout << "Invalid choice." << endl; } } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
