1. 程式人生 > >棧的實現及括號匹配

棧的實現及括號匹配

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#define max 50;
typedef char type;
typedef struct
{
    type data[50];
    int top;
}stack;
void initialstack(stack *s)
{
    s->top = 0;
}
int push(stack *s, type x)
{
    if (s->top == 50)
        return -1;
    s->data[s->top++] = x;
    return 0;
}
type pop(stack *s)
{
    if (s->top == 0)
        return -2;
    type x = s->data[--s->top];
    return x;
}
void kuohaomatch1()
{
    //基本思想掃描每一個字元,遇到花中圓的左括號進棧,
    //遇到花中圓的右括號時檢查是否為相應的左括號若不是則匹配失敗
    char s[50];
    int i = 0;
    char d = 'a';
    scanf_s("%c", &d);
    while (d != ' '&&i<50)
    {
        s[i++] = d;
        scanf_s("%c", &d);
    }
    s[i] = '\0';
    stack *s1 = (stack *)malloc(sizeof(stack));
    stack *s2 = (stack *)malloc(sizeof(stack));
    initialstack(s1);
    initialstack(s2);
    for (i = 0; s[i] != '\0'; i++)
        switch (s[i])
    {
        case'{':push(s1, '}'); break;
        case'(':push(s1, ')'); break;
        case'[':push(s1, ']'); break;
        default:
            if (pop(s1) != s[i])
                printf("不匹配");
            else
                printf("匹配");

    }
    printf("匹配");
    getchar();
    getchar();
}