第四章 栈和队列
1.栈:限定仅在表尾进行插入或删除操作的线性表,表尾端称为栈顶,表头端称为栈底。栈顶移动,栈底固定。特点:先进后出、后进先出
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
Status Push(SqStack &S,SElemType e)
{
if(S.top==MAXSIZE-1)
return ERROR;
S.data[++S.top]=e;
return OK;
}
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==-1)
return ERROR;
e=S.data[S.top--];
return OK;
}
2.两栈共享空间
typedef struct
{
SElemType data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
Status Push(SqDoubleStack &S,SElemType e,int sNum)
{
if(S.top1+1==S.top2)
return ERROR;
if(sNum)
S.data[--S.top2]=e;
else
S.data[++S.top1]=e;
return OK;
}
Status Pop(SqDoubleStack &S,SElemType &e,int sNum)
{
if(sNum)
{
if(S.top2==MAXSIZE)
return ERROR;
e=S.data[S.top2++];
}
else
{
if(S.top1==-1)
return ERROR;
e=S.data[S.top1--];
}
return OK;
}
3.栈的链式存储结构
栈空条件:S.top==NULL
typedef struct StackNode
{
SElemType data;
StackNode *next;
}StackNode,*LinkStackPtr;
typedef struct LinkStack
{
LinkStackPtr top;
int count;
}LinkStack;
Status Push(LinkStack &S,SElemType e)
{
LinkStackPtr s;
s=(LinkStackPtr)malloc(sizeof(StackNode));
s->data=e;
s->next=S.top;
S.top=s;
S.count++;
return OK;
}
Status Pop(LinkStack &S,SElemType &e)
{
if(S.top==NULL)
return ERROR;
e=S.top->data;
LinkStackPtr p=S.top;
S.top=S.top->next;
S.count--;
free(p);
return OK;
}
4.队列:队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。先进先出 允许插入的一端称为队尾,允许删除的一端称为队头。
5.循环队列
typedef struct
{
int front,rear;
QElemtype data[MAXSIZE];
}SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.front=0;
Q.rear=0;
return OK;
}
Status Push(SqQueue &Q,QElemtype e)
{
if((Q.rear+1)%MAXSIZE==Q.front)
return ERROR;
else
{
Q.data[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXSIZE;
}
}
Status Pop(SqQueue &Q,QElemtype &e)
{
if(Q.rear==Q.front)
return ERROR;
else
{
e=Q.data[Q.front];
Q.front=(Q.front+1)%MAXSIZE;
}
}
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
6.链栈
typedef struct Qnode
{
int data;
Qnode *next;
}Qnode,*Qlink;
typedef struct
{
Qlink front,rear;
}LinkQueue;
Status EnQueue(LinkQueue &Q,int e)
{
Qlink p;
p=(Qlink)malloc(sizeof(Qnode));
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;
}
Status DeQueue(LinkQueue &Q,int &e)
{
Qlink p;
if(Q.front==Q.rear)
return ERROR;
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
return OK;
}