#include "iostream"
using namespace std;
typedef struct student
{
int data;
struct student * next;
}node;//定义结构体节点
typedef struct linkqueue
{
node * first;
node * rear;
}stack;//定义队列结构,首指针和尾指针
/*********************************
函数名:void initstack(stack *st)
功能:初始化栈
*/
void initstack(stack *st)
{
st->first=st->rear=NULL;
}
/*********************************
函数名:stack *push(stack *st,int x)
功能:向栈顶添加一个元素
*/
stack *push(stack *st,int x)
{
node *s;
s=new node;
s->data=x;
s->next=NULL;
if (st->rear==NULL)
{
st->rear=s;
st->first=s;
}
else
{
st->first->next=s;
st->first=s;
}
return st;
}
/*********************************
函数名:int pop(stack *st)
功能:向栈顶取出一个元素
*/
int pop(stack *st)
{
int num=0;
if ((st->first==st->rear)&&st->first!=NULL)
{
num=st->first->data;
st->first=st->rear=NULL;
return num;
}
else if (st->rear==NULL&&st->first==NULL)
{
cout<<"已全部出栈\n";
exit(0);
}
else if(st->first!=st->rear)
{
node *p;
p=st->rear;
while (p->next!=st->first)
{
p=p->next;
}
num=st->first->data;
st->first=p;
return num;
}
}
/*********************************
函数名:int leng(stack *st)
功能:返回栈长度,即元素个数
*/
int leng(stack *st)
{
node *p=st->rear;
int ct=0;
if (st->rear==NULL&&st->first==NULL)
{
return 0;
}
else if ((st->first==st->rear)&&st->first!=NULL)
{
return 1;
}
else
{
while (p!=st->first)
{
ct++;
p=p->next;
}
return ct+1;
}
}
/*********************************
函数名:void printall(stack*st)
功能:输出栈中所有元素,栈指针位置不变
*/
void printall(stack*st)
{
node *q=st->first;
while (st->first!=st->rear)
{
node *p=st->rear;
cout<<" 出栈 :"<<st->first->data<<" ,";
while (p->next!=st->first)
{
p=p->next;
}
st->first=p;
}
cout<<"出栈 :"<<st->first->data<<endl;
st->first=q;
}
/*********************************
函数名:int isempty(stack *st)
功能:判断栈是否为空
*/
int isempty(stack *st)
{
if (st->rear==NULL&&st->first==NULL)
{
return 1;
}
else
{
return 0;
}
}
/*********************************
函数名:int readelement(stack *st)
功能:从栈顶读一个元素
*/
int readelement(stack *st)
{
if (st->first!=NULL)
{
return st->first->data;
}
}
/*********************************
函数名:void main()
功能:测试各个模块
*/
void main()
{
stack st;
initstack(&st);
for (int i=0;i<5;i++)
{
push(&st,i+1);
}
printall(&st);
cout<<"length is: "<<leng(&st)<<endl;
cout<<"POP: "<<pop(&st)<<endl;
cout<<"剩余:\n";
printall(&st);
cout<<"length is: "<<leng(&st)<<endl;
if (isempty(&st)==1)
{
cout<<"stack is empty\n";
}
else
{
cout<<"stack is not empty\n";
}
cout<<"read a element: "<<readelement(&st)<<endl;
cout<<pop(&st)<<endl;;
cout<<pop(&st)<<endl;
cout<<pop(&st)<<endl;
cout<<pop(&st)<<endl;;
if (isempty(&st)==1)
{
cout<<"stack is empty\n";
}
else
{
cout<<"stack is not empty\n";
}
push(&st,1);
cout<<"length is: "<<leng(&st)<<endl;
cout<<"read a element: "<<readelement(&st)<<endl;
printall(&st);
cout<<"出栈: "<<pop(&st)<<endl;
cout<<"length is: "<<leng(&st)<<endl;
}
程序运行结果: