#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct list
{
int data;
struct list *next;
}node;
typedef struct listStack
{
node *top;
node *bottom;
}stack;
stack *createStack()
{
node *p;
stack *s = (stack *)malloc(sizeof(stack));
s->top = NULL;
s->bottom = NULL;
int x;
while(1)
{
cout<<"input element of stack(0 to exit):"<<endl;
cin>>x;
if(x != 0)
{
if(s->top == NULL)
{
s->top = (node *)malloc(sizeof(node));
s->top->data = x;
s->bottom = s->top;
}
else
{
p = (node *)malloc(sizeof(node));
p->data = x;
p->next = s->top;
s->top = p;
}
}
else
{
cout<<"create stack finished!"<<endl;
break;
}
}
return s;
}
stack *push(stack *s, int x)
{
node *p = (node *)malloc(sizeof(node));
p->data = x;
p->next = s->top;
s->top = p;
return s;
}
void display(stack *s)
{
node *p = s->top;
if(p == NULL)
{
cout<<"Empty Stack!"<<endl;
return ;
}
cout<<"stack elements:"<<endl;
while(p != s->bottom)
{
cout<<p->data<<endl;
p = p->next;
}
cout<<p->data<<endl;
return ;
}
stack *pop(stack *s, int &x)
{
if(s->top == NULL)
{
cout<<"Empty Stack!"<<endl;
return s;
}
else if(s->top == s->bottom)
{
node *p = s->top;
x = p->data;
s->top = NULL;
s->bottom = NULL;
free(p);
return s;
}
else
{
node *p = s->top;
x = p->data;
s->top = p->next;
free(p);
return s;
}
}
int length(stack *s)
{
int count = 0;
node *p;
p = s->top;
while(1)
{
if(p == s->bottom)
break;
else
{
count++;
p = p->next;
}
}
if(p != NULL)
{
count++;
}
return count;
}
int main()
{
int x;
stack *s = createStack();
display(s);
cout<<"length of stack:"<<length(s)<<endl;
cout<<"element to push:"<<endl;
cin>>x;
s = push(s, x);
cout<<"After push:"<<endl;
display(s);
cout<<"length of stack:"<<length(s)<<endl;
cout<<"After pop:"<<endl;
s = pop(s, x);
display(s);
cout<<"length of stack:"<<length(s)<<endl;
cout<<"pop element:"<<x<<endl;
free(s);
return 0;
}