栈应用:平衡符号

代码实现:

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

struct StackRecord
{
    
    
    int Capacity;
    int TopOfStack;
    char *Array;
    
};

typedef struct StackRecord *Stack;
Stack CreateStack(int MaxElem)
{
    
    
    Stack S;
    S=(StackRecord *)malloc(sizeof(struct StackRecord));
    if(S==NULL)
        printf("Out of space!1");
    S->Array=(char *)malloc(sizeof(char)*MaxElem);
    if(S->Array==NULL)
        printf("Out of space!2");
    S->Capacity=MaxElem;
    S->TopOfStack=-1;
    return S;
}
void DisposeStack(Stack S)
{
    
    
    if(S!=NULL)
    {
    
    
        free(S->Array);
        free(S);
    }
}
int IsEmpty(Stack S)
{
    
    
    return S->TopOfStack==-1;
}
int IsFull(Stack S)
{
    
    
    return S->TopOfStack==S->Capacity-1;
}
void Push(Stack S,int x)
{
    
    
    if(IsFull(S))
        printf("Out of space!3");
    else 
        S->Array[++S->TopOfStack]=x;
}
char Top(Stack S)
{
    
    
    if(IsEmpty(S))
    {
    
    
        printf("Empty Stack!");return 0;
    }
    else
        return S->Array[S->TopOfStack];
        
}
void Pop(Stack S)
{
    
    
    if(IsEmpty(S))
        printf("Empty Stack!");
    else
        S->TopOfStack--;
}
int main(void) {
    
     
    char str[100];
    scanf("%s",str);
    int length=strlen(str);
    Stack S=CreateStack(length+1);
    for (int i=0;i<length;i++)
    {
    
    
        if(str[i]=='('||str[i]=='{'||str[i]=='[')
            Push(S,str[i]);
        else if(str[i]==')'&&Top(S)=='(')
            Pop(S);
        else if(str[i]==']'&&Top(S)=='[')
            Pop(S);
        else if(str[i]=='}'&&Top(S)=='{')
            Pop(S);
    }
    if(IsEmpty(S))
	    printf("match!匹配成功!");
	else
	    printf("don't match!匹配失败!");
}

猜你喜欢

转载自blog.csdn.net/su_1998/article/details/121859523