Stack in Linklist
Stack in Linklist
class node
{
public:
int data;
node *next;
};
class stack
{
public:
int stksize;
node* head;
stack()
{
head = NULL;
stksize = 0;
}
void push(int val)
{
node *temp = new node();
temp->data = val;
temp->next = head;
head = temp;
cout<<"Element popped!"<<endl;
stksize--;
}
int top()
{
if(head==NULL)
{
cout<<"No top element! stack is empty: "<<endl;
return -1;
}
cout<<"Top element is "<<head->data<<endl;
return head->data;
}
void display()
{
node *temp = head;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int size()
{
cout<<"size of stack is:"<<stksize<<endl;
return stksize;
}
int empty()
{
if(head==NULL)
{
cout<<"stack is empty"<<endl;
return 1;
}
cout<<"Stack is not empty!"<<endl;
return 0;
}
};
int main()
{
stack s1;
int size,i,num;
cout<<"Enter the size of stack: ";
cin>>size;
for(i=1;i<=size;i++)
{
cin>>num;
s1.push(num);
s1.display();
}
//s1.pop();
s1.top();
s1.size();
s1.empty();
return 0;
}