目录
3.1栈和队列的定义和特点
3.2案例引入
3.3栈的实现和操作的实现
顺序栈的表示
顺序栈初始化
顺序栈是否为空
顺序表长度
清空顺序栈
销毁顺序栈
顺序栈的入栈
顺序栈的出栈
链栈的表示
链栈的初始化
链栈是否为空
链栈的入栈
链栈的出栈
取栈顶元素
3.4栈和递归
3.5队列的表示和操作的实现
顺序队表示
链队表示
3.6案例分析与实现
#define MAXSIZE 100
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &S){
S.base = new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
Status StackEmpty(SqStack S){
if(S.top == S.base)
return OK;
else
return FALSE;
}
int StackLength(SqStack S){
return S.top - S.base;
}
Status ClearStack(SqStack S){
if(S.base) S.top = S.base;
return OK;
}
Status DestoryStack(SqStack &S){
if(!S.base){
delete S.base;
S.stacksize = 0;
S.base = S.top = NULL;
}
return OK;
}
Status Push(SqStack &S,SElemType e){
if(S.top - S.base == S.stacksize)
return ERROR;
*S.top++=e;
return OK;
}
Status Pop(SqStack &S,SElemType &e){
if(S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
typedef struct StackNode{
SElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
LinkStack S;
void InitStack(LinkStack &S){
S = NULL;
return OK;
}
Status StackEmpty(LinkStack S){
if(S==NULL) return TRUE;
else return FALSE;
}
Status Push(LinkStack &S,SElemType e){
p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S,SElemType &e){
if(S==NULL) return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
SElemType GetTop(LinkStack S){
if(S!-NULL){
return S->data;
}
}
#define MAXQSIZE 100
typedef struct{
QElemType *base;
int front;//头指针
int rear;//尾指针
}SqQueue;
Status InitQueue(SqQueue &Q){
Q.base = new QElemType[MAXQSIZE];
if(!Q.base) exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
int QueueLength(SqQueue Q){
return ((Q.rear-Q.front+MAXQSIZE)%MAXQSIZE);
}
Status EnQueue(SqQueue &Q,QElemType e){
if((Q.rear+1)%MAXSIZE==Q.front) return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e){
if(Q.front==Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front+1)%MAXQSIZE;
return OK;
}
SElemType GetHead(SqQueue Q){
if(Q.front != Q.rear)
return Q.base[Q.front];
}
#define MAXQSIZE 100
typedef struct Onode{
QElemType data;
struct Qnode *next;
}QNode, *QuenePtr;
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
Status DestoryQueue(LinkQueue &Q){
while(Q.front){
p = Q.front->next;
free(Q.front);
Q.front = p;
}
return OK;
}
Status EnQueue(LinkQueue &Q,QElemType e){
p = (QueuePtr)malloc(sizeof(QNode));
if(!p) exit(OVERFLOE);
p->data = e;p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
Status DeQueue(LinkQueue &Q,QElemType &e){
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;
delete p;
return OK;
}