I wrote a small C++ program which implements basic operations of stack using linkedLists in C++. While testing that program I observed a strange issue with cout. In main function,
int main()
{
stack *MainStack=new stack();
MainStack->push(1);
MainStack->push(2);
std::cout<<MainStack->pop();
std::cout<<MainStack->pop();
}
The output is 21 and when main function is
int main()
{
stack *MainStack=new stack();
MainStack->push(1);
MainStack->push(2);
std::cout<<MainStack->pop()<<MainStack->pop();
}
The output is 12.
What is the reason for that error? Can anyone give me reason for this error.
My C++ program is
#include<iostream>
class stack
{
int value;
stack *next;
public:
stack()
{
value=0;
next=NULL;
}
stack(int data)
{
value=data;
next=NULL;
}
void push(int data)
{
stack *temp;
temp=next;
next=new stack(data);
next->next=temp;
value++;
}
int pop()
{
int data;
if(next==NULL)
{
std::cout<<"Underflow\n";
return -1;
}
stack *temp=next;
next=next->next;
data=temp->value;
delete(temp);
value--;
return data;
}
int top()
{
return next->value;
}
bool isStackEmpty()
{
if(next==NULL)
{
return true;
}
else
{
return false;
}
}
int getCount()
{
return value;
}
};
int main()
{
stack *MainStack=new stack();
MainStack->push(1);
MainStack->push(2);
std::cout<<MainStack->pop()<<MainStack->pop();
}