C++ stack using linked list One problem here: 1.The display function displays: \
ID: 3679367 • Letter: C
Question
C++ stack using linked list
One problem here:
1.The display function displays: "The stack is NULL"
2. Then I try to pop again. The program terminates without displaying: "The stack is empty" . In the pop function it says (top==NULL), display: The stack is empty .
#include<iostream>
using namespace std;
// Creating a NODE Structure
struct node
{
int data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *top;
public:
stack() // constructer
{
top=NULL;
}
void push(); // to insert an element
void pop(); // to delete an element
void show(); // to show the stack
};
// PUSH Operation
void stack::push()
{
int value;
struct node *ptr;
cout<<"Enter a number to insert: ";
cin>>value;
ptr=new node;
ptr->data=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
}
// POP Operation
void stack::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"The stack is empty!!!";
}
temp=top;
top=top->next;
cout<<"The Poped value is "<<temp->data << endl;
delete temp;
}
// Show stack
void stack::show()
{
struct node *temp=top;
cout<<"The stack is ";
while(temp!=NULL)
{
cout<<temp->data<<" ->";
temp=temp->next;
}
cout<<"NULL"<< endl;
}
// Main function
int main()
{
stack s;
int choice;
cout<<"Stack using linkedlist"<< endl<< endl;
while(1)
{
cout<<"Enter your choice(1-4): ";
cout<<"1:PUSH 2:POP 3:DISPLAY 4:EXIT";
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
return 0;
break;
default:
cout<<"Please enter correct choice(1-4)!!";
break;
}
}
return 0;
}
where to post my questions
Explanation / Answer
there is no problem in the code it self.
you are miss understand the logic.what it is when stack is empty how can we pop and display. you can do push operation.
you can post questions in chegg.com and you need currect information its better to contact with MNV territory managers and coordinators
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.