#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int SElemType;
typedef int Status;
typedef int QElemType;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define error 1
#define OK 0
#define OVERFLOW -1
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
} SqStack;
typedef struct QNode
{
QElemType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr mfront;
QueuePtr mrear;
} LinkQueue;
Status InitStack(SqStack &S)//构造一个空栈
{
S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base)
{
cout << "失败";
exit(0);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
int GetTop(SqStack S, SElemType &e)
{
//若栈不空,用e返回栈顶元素
if (S.top == S.base)
{
cout << "空";
return error;
}
e = *(S.top - 1);
return OK;
}
int Push(SqStack &S, SElemType e)
{
//插入元素e为新的栈顶元素
if (S.top - S.base >= S.stacksize)//栈满,追加存储空间
{
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
if (!S.base)
{
exit(0);
}
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
int Pop(SqStack &S, SElemType &e)
{
//若栈不空则删除栈顶元素,用e返回其值
if (S.top == S.base)
{
return error;
}
e = *--S.top;
return OK;
}
Status InitQueue(LinkQueue &Q)//构造一个空队列
{
Q.mfront=Q.mrear=(QueuePtr)malloc(sizeof(QNode));
if(!Q.mfront)
{
cout<<"分配失败"<<endl;
exit(OVERFLOW);
}
Q.mfront->next=NULL;
return OK;
}
Status DestroyQueue(LinkQueue &Q) //销毁队列
{
while(Q.mfront)
{
Q.mrear=Q.mfront->next;
free(Q.mfront);
Q.mfront=Q.mrear;
}
return OK;
}
Status EnQueue(LinkQueue &Q,QElemType e)//插入元素e为Q的新的队尾元素
{
QNode *p;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p)
{
cout<<"分配失败"<<endl;
exit(OVERFLOW);
}
p->data=e;
p->next=NULL;
Q.mrear->next=p;
Q.mrear=p;
return OK;
}
Status DeQueue(LinkQueue &Q,QElemType &e)
{
//若队列不空,则删除Q的队头元素,用e返回其值,否则返回error
QNode *p;
if(Q.mfront==Q.mrear)
{
cout<<"空"<<endl;
return error;
}
p=Q.mfront->next;
e=p->data;
Q.mfront->next=p->next;
if(Q.mrear==p)Q.mrear=Q.mfront;
free(p);
return OK;
}
Status GetQueueHead(LinkQueue &Q,QElemType &e)
{
//若队列不空,则删除Q的队头元素,用e返回其值,否则返回error
QNode *p;
if(Q.mfront==Q.mrear)
{
cout<<"空"<<endl;
return error;
}
p=Q.mfront->next;
e=p->data;
return OK;
}
int main()
{
LinkQueue q;
InitQueue(q);
for(int i=0;i<5;i++)
{
EnQueue(q,i);
}
int n;
GetQueueHead(q,n);
cout<<n<<endl;
DeQueue(q, n);
cout<<n<<endl;
GetQueueHead(q,n);
cout<<n<<endl;
DestroyQueue(q);
return 0;
}