C语言用栈的思想判断括号是否匹配

#include 
#include 

typedef char DataType;
typedef struct stacknode
{
     
    DataType data;
    struct stacknode *next;
} LinkStack;

LinkStack *InitStack()
{
     
    LinkStack *S;
    S = NULL;
    return S;
}

int EmptyStack(LinkStack *S)
{
     
    if (S == NULL)
        return 1;
    else
        return 0;
}

LinkStack *Pop(LinkStack *S, DataType *x)
{
     
    LinkStack *p;
    if (EmptyStack(S))
    {
     
        printf("\t 栈空,不能出栈!");
        return NULL;
    }
    else
    {
     
        *x = S->data;
        p = S;
        S = S->next;
        free(p);
        return S;
    }
}

LinkStack *Push(LinkStack *S, DataType x)
{
     
    LinkStack *p;
    p = (LinkStack *)malloc(sizeof(LinkStack));
    p->data = x;
    p->next = S;
    S = p;
    return S;
}

int GetTop(LinkStack *S, DataType *x)
{
     
    if (EmptyStack(S))
    {
     
        printf("\t 栈空!");
        return 0;
    }
    else
    {
     
        *x = S->data;
        return 1;
    }
}

void ShowStack(LinkStack *S)
{
     
    LinkStack *p = S;
    if (EmptyStack(S))
    {
     
        printf("\t 栈空!");
    }
    else
    {
     
        printf("从栈顶元素起栈中各元素为:");
        while (p != NULL)
        {
     
            printf("%2d", p->data);
            p = p->next;
        }
    }
}

void ParenMatch(LinkStack *S, DataType *y)
{
     
    char *paren = y;
    char x;
    for (int i = 0; paren[i] != '\0'; i++)
    {
     
        switch (paren[i])
        {
     
        case '(':
        case '[':
        case '{':
            S = Push(S, paren[i]);
            break;

        case ')':
            S = Pop(S, &x);
            if (x != '(')
            {
     
                printf("括号不匹配");
                return;
            }
            break;

        case ']':
            S = Pop(S, &x);
            if (x != '[')
            {
     
                printf("括号不匹配");
                return;
            }
            break;

        case '}':
            S = Pop(S, &x);
            if (x != '{')
            {
     
                printf("括号不匹配");
                return;
            }
            break;

        default:
            break;
        }
    }
    if (EmptyStack(S))
        printf("所有括号都匹配");
    else
        printf("括号不匹配");
}

int main()
{
     
    int x;
    LinkStack *Stack;
    Stack = InitStack(Stack);
    char *y;
    char *n;
    y = "{[(1+2)-3]*4}";
    n = "{[(1+2-3]*4}";
    ParenMatch(Stack, n);

    return 0;
}

你可能感兴趣的:(栈,数据结构,算法,c语言)