栈
一.栈的顺序存储结构及其基本运算的实现
1.基本运算
(1).初始化栈
void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; }
(2).销毁栈
void DestroyStack(SqStack *&s) { free(s); }
(3).判断栈是否为空
bool StackEmpty(SqStack *s) { return(s->top==-1); }
(4).进栈
bool Push(SqStack *&s,ElemType e) { if (s->top==MaxSize-1) //栈满的情况,即栈上溢出 return false; s->top++; s->data[s->top]=e; return true; }
(5).出栈
bool Pop(SqStack *&s,ElemType &e) { if (s->top==-1) //栈为空的情况,即栈下溢出 return false; e=s->data[s->top]; s->top--; return true; }
(6).取栈顶元素
bool GetTop(SqStack *s,ElemType &e) { if (s->top==-1) //栈为空的情况,即栈下溢出 return false; e=s->data[s->top]; return true; }
(7).求栈中元素的个数
int StackLength(SqStack *s) //返回栈中元素个数——栈长度 { return(s->top+1); }
(8).输出栈
void DispStack(SqStack *s) //输出栈 { int i; for (i=s->top;i>=0;i--) printf("%c ",s->data[i]); printf("\n"); }
2.应用示例
(1).设计一个算法利用顺序栈判断一个字符串是否为对称串。
bool symmetry(ElemType str[]) { int i; ElemType e; SqStack *st; InitStack(st); for(i=0;str[i]!='\0';i++) Push(st,str[i]); for(i=0;str[i]!='\0';i++) { Pop(st,e); if(str[i] != e) { DestroyStack(st); return false; } } DestroyStack(st); return true; }
二.栈的链式存储结构及其基本运算的实现
1.基本运算
(1).初始化栈
void InitStack(LinkStStack *&s) //初始化栈 { s=(LinkStStack *)malloc(sizeof(LinkStStack)); s->next=NULL; }
(2).销毁栈
void DestroyStack(LinkStStack *&s) //销毁栈 { LinkStStack *p=s->next; while (p!=NULL) { free(s); s=p; p=p->next; } free(s); //s指向尾结点,释放其空间 }
(3).判断栈是否为空
bool StackEmpty(LinkStStack *s) //判断栈是否为空 { return(s->next==NULL); }
(4).进栈
void Push(LinkStStack *&s,ElemType e) //入栈 { LinkStStack *p; p=(LinkStStack *)malloc(sizeof(LinkStStack)); p->data=e; //新建元素e对应的节点*p p->next=s->next; //插入*p节点作为开始节点 s->next=p; }
(5).出栈
bool Pop(LinkStStack *&s,ElemType &e) //出栈 { LinkStStack *p; if (s->next==NULL) //栈空的情况 return false; p=s->next; //p指向开始节点 e=p->data; s->next=p->next; //删除*p节点 free(p); //释放*p节点 return true; }
(6).取栈顶元素
bool GetTop(LinkStStack *s,ElemType &e) //取栈顶元素 { if (s->next==NULL) //栈空的情况 return false; e=s->next->data; return true; }
(7).求栈的长度
int StackLength(LinkStStack *s) //返回栈长度 { int i=0; LinkStStack *p; p=s->next; while (p!=NULL) { i++; p=p->next; } return(i); }
(8).输出栈中元素
void DispStack(LinkStStack *s) //输出栈中元素 { LinkStStack *p=s->next; while (p!=NULL) { printf("%c ",p->data); p=p->next; } printf("\n"); }
2.应用示例
(1).设计一个算法判断输入的表达式中括号是否配对(假设只含有左、右圆括号)
bool Match(char exp[],int n) { int i=0; char e; bool match = true; LinkStNode *st; InitStack(st); while(i<n && match) { if(exp[i] == '(') Push(st,exp[i]); else if(exp[i] == ')') { if(GetTop(st,e) == true) { if(e != '(') match = false; else Pop(st,e); } else //无法取栈顶元素时表示不匹配 match = false; } i++; } if(!StackEmpty(st)) match = false; DestroyStack(st); return match; }