#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data; //data
node *next; //link
};
class stack // stack using linked list
{
public:
node *top; // top element of stack
public:
stack()
{
top= NULL;
}
void push(int value)
{
node *temp = new node; // create a new node
temp-> data = value;
temp-> next = NULL;
if(top==NULL) // stack is empty
{
top=temp;
temp=NULL;
}
else
{
temp-> next = top;
top=temp;
temp=NULL;
}
}
//template <class X>
void pop()
{
if(top==NULL)
{
cout<<"\nStackOverflow "<<endl;
cout<<"Program Terminated "<<endl;
exit (0);
}
else
{
top=top->next;
}
}
void display()
{
node *temp=new node;
temp=top;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp-> next;
}
while(top==NULL)
{
cout<<"\nStack is Empty "<<endl;
exit (0);
}
}
};
int main()
{
stack a;
a.push(5);
a.display();
a.push(10);
a.display();
a.pop();
a.pop();
a.push(20);
a.display();
a.pop();
a.display();
return 0;
}
The Output of this code is 5 10 5 20 Stack is Empty.
Which is wrong output and the correct output is 5 10 20 Stack is Empty..
Anyone tell me why this errors occured.
The Refrence of the code :[Implementation of stack using Templates and And Linked List in c++
displayfunction have a memory leak.nodeindisplay()?node *temp=new node;tonode *temp;. There's no need to allocate a node there because the very next line saystemp=top;Your version allocates a node and then throws it away, a.k.a a memory leak.