顺序栈,链栈及其应用——括号匹配算法
#include<stdio.h>
#include<stdlib.h>
#define maxn 100
typedef struct //顺序栈;
{
char elem[maxn];
int top;
}SeqStack;
void InitStack(SeqStack *S)
{
S->top=-1;
}
void Push(SeqStack *S,char x)
{
if(S->top==maxn-1) return;
S->top++;
S->elem[S->top]=x;
}
void Pop(SeqStack *S,char *x)
{
if(S->top==-1) return;
else{
*x=S->elem[S->top--];
}
}
void GetTop(SeqStack *S,char *x)
{
if(S->top==-1) return;
else{
*x=S->elem[S->top];
}
}
typedef struct node //链栈;
{
char data;
struct node *next;
}LinkStackNode,*LinkStack;
void InitLink(LinkStack L)
{
L=(LinkStackNode*)malloc(sizeof(LinkStackNode));
L->next=NULL;
}
void push(LinkStack top,char x)
{
LinkStackNode *temp;
temp=(LinkStackNode*)malloc(sizeof(LinkStackNode));
if(temp==NULL) return;
temp->data=x;
temp->next=top->next;
top->next=temp;
}
void pop(LinkStack top,char *x)
{
LinkStackNode *temp;
temp=top->next;
if(temp==NULL) return;
top->next=temp->next;
*x=temp->data;
free(temp);
}
bool Match(char x,char y)
{
if((x=='('&&y==')')||(x=='['&&y==']')||(x=='{'&&y=='}')) return true;
else return false;
}
void BrachetMach(char *str) //括号匹配算法;
{
SeqStack S;
int i;
char ch;
InitStack(&S);
for(int i=0;str[i]!='\0';i++){
switch(str[i]){
case'(':
case'[':
case'{':
Push(&S,str[i]);
break;
case')':
case']':
case'}':
if(S.top==-1){
printf("\n右括号多余!");
return;
}
else{
GetTop(&S,&ch);
if(Match(ch,str[i])) Pop(&S,&ch);
else{
printf("\n对应左右括号不匹配!");
return;
}
}
}
}
if(S.top==-1) printf("\n括号匹配");
else printf("\n左括号多余!");
}
int main()
{
SeqStack s;
LinkStackNode l;
char c;
char str[100];
InitStack(&s);
InitLink(&l);
c='a';
for(int i=0;i<10;i++){
Push(&s,c);
c++;
}
for(int i=0;i<10;i++){
Pop(&s,&c);
printf("%c ",c);
}
printf("\n");
c='A';
for(int i=0;i<10;i++){
push(&l,c);
c++;
}
for(int i=0;i<10;i++){
pop(&l,&c);
printf("%c ",c);
}
printf("\n");
scanf("%s",str);
BrachetMach(str);
return 0;
}