# define MaxSize 50
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack
void InitStack(SqStack &s){
s.top=-1;
}
bool StackEmpty(SqStack &s){
if(s.top==-1) return true;
else return false;
}
bool push(Sqstack &s,ElemType x){
if(s.top==MaxSize-1) return false;
s.data[++top]=x;
return true;
}
bool pop(SqStack &s,ElemType &x){
if(s.top==-1) return false;
x=s.data[top--];
return true;
}
bool getTop(SqStack &s,ElemType &x){
x=s.data[top];
return true;
}
typedef struct LinkNode{
ElemType data;
Struct LinkNode *next;
}*LiStack
**注意:所有操作均在单链表的表头进行
- 三、栈的应用
- 单链表的表头指针为L,设计算法判断该链表的全部n个字符是否中心对称
bool isCentral(LinkList L){
int n=L.length(L);
LNode *p=L->next;
int i;
char data[n/2];
for(i=0;i<n/2;i++){
data[i]=p->data;
p=p->next;
}
i--;
if(n%2==1) p=p->next;
while(p!=NULL&&data[i]==p->data){
i--;
p=p->next;
}
if(i==-1) return true;
return false
}
- 栈s1、s2采用顺序栈的方式,且共享一个存储区[0,…maxSize],采用栈顶相向、迎面增长的方式存储,设计s1、s2有关入栈、出栈的相关操作
#define MaxSize 100
typedef strecu{
ElemType data[MaxSize];
int top1,top2;
}SqStack
bool push(SqStack &s,ElemType x,int num){
if(s.top2-s.top1==1)
return false;
switch(num){
case 1://对s1进行入栈
s.data[++top1]=x; break;
case 2://对s2进行入栈
s.data[--top2]=x; break;
}
return true;
}
bool pop(SqStack &s,ElemType &x,int num){
if(s.top1==-1&&s.top2==MaxSize) return false;
switch(num){
case 1:
x=s.data[top1--]; break;
case 2:
x=s.data[top2++]; break;
}
return true;
}
bool Match(char A[]){
InitStack(S);
int i=0;
char x;
if(A[i]!='\0'){
switch(A[i]){
case'(':
case'[':
case'{':
push(S,A[i]);
break;
case')':
pop(S,x);
if(x!='(')
return false;
break;
case']':
if(x!=']')
return false;
break;
case'}':
if(x!='}')
return false;
break;
}
i++;
}
if(StackEmpty(S)!=NULL) return false;
return true;
}
int Reverse(int N){
InitStack(S);
int i,result=0;
while(N!=0){
i=N%2;
N=N/2;
push(S,i);
}
while(StackEmpty(S)!=NULL){
pop(S,i);
result=result*10+i;
}
return result;
}