第3章限定性线性表——栈和队列.doc
文本预览下载声明
第3章 限定性线性表——栈和队列
3.15?
#define StackSize 100;
typedef struct {
? SElemType? *base;
? SElemType? *top0;
? SElemType? *top1;
}TSqStack;
Status InitStack(TSqStack tws){
? //构造一个空的双向栈
? if (!(tws.base=(SElemType *)malloc(StackSize*sizeof(SElemType))))exit(OVERFLOW);
? tws.top0=tws.base;
? tws.top1=tws.base[StackSize-1];
? return OK;
}
Status Push(TSqStack tws, int i, SElemType x){
? //将元素x压入双向栈tws的第i个栈中,i=0,1
? if (tws.top0==tws.top1+1)exit(OVERFLOW);
? if (i==0) *tws.top0++=x;
? else if (i==1) *tws.top1--=x;
? else return ERROR;
? return OK;
}
SElemType Pop(TSqStack tws, int i){
? //若双向栈tws的第i个栈不空,则删除第i个栈的栈顶元素并返回其值,否则返回空元素
? if (i!=0||i!=1) return NULL;
? if (i==0tws.top0) return *--tws.top0;
? if (i==1tws.top1!=tws.base[StackSize-1]) return *++tws.top1;
? return NULL;
}
3.17?
Status Model(){
? //识别依次读入的一个以@为结束符的字符序列是否为形如‘序列1序列2’模式的字符序列
? //序列1和序列2中不包含字符‘’,序列1是序列2的逆序列
? InitStack(s);? c=getchar();
? while (c!=) {Push(s,c); c=getchar();}
? c=getchar();
? while (c!=@!StackEmpty(s)) {
??? Pop(s,x);
??? if (c==x) c=getchar();
??? else return FALSE;
? }
? if (c==@ StackEmpty(s)) return TRUE;
? else return FALSE;
}?
3.19
Status BracketsMatch(){
? //判断依次读入的以‘@’为结束符的算术表达式中括号是否正确配对出现
? InitStack(s);? c=getchar();
? while (c!=@){
??? if ( c==( || c==[ || c=={) Push(s,c);
??? if ( c==) || c==] || c==}){
?????? if EmptyStack(s) return FALSE;
?????? Pop(s,x);
?????? if (!((x==(c==))||(x==[c==])||(x=={c==}))) return FALSE;
??? }//if
??? c=getchar();
? }//while
? if EmptyStack(s) return TRUE;
? else return FALSE;
}
3.28
typedef struct CQNode {
? CQElemType???? data;
? struct CQNode? *next;
}CQNode, *CQueuePtr;
typedef struct {
? CQueuePtr? rear;
}CLinkQueue;
Status InitCQueue(CLinkQueue cq) {
? //初始化一个只有尾指针的带头结点的循环链表表示的队列
? if (!(cq.rear=(CQueuePtr)malloc(sizeof(CQNode))) exit(OVERFLOW);
? cq.rear-next=cq.rear;
? return OK;
}
Status EnCQueue(CLinkQueue cq, CQElemType e){
? //插入元素e为cq的新的队尾元素
? if (!(p=(CQueuePtr)malloc(sizeof(CQNode)))) exit(OVERFLOW);
? p-data=e;?
显示全部