⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 g.cpp

📁 /* 测试括号是否匹配 */
💻 CPP
字号:
/* 测试括号是否匹配 */
#include<malloc.h>
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
typedef struct node_link
{
    char data;
    struct node_link *next;
}node;
node *top=NULL;
/* 压栈 */
void push(char data)
{
    node *p;
    
    p=(node *)malloc(sizeof(node));
    if(!p){
        printf("push failed.\n");
        exit(0);
    }
    p->data=data;
    p->next=top;
    top=p;
}
/* 出栈 */
int pop()
{
    node *p;
    int get;
    
    p=top;
    get=top->data;
    top=top->next;
    free(p);
    
    return get;
}
/* 取栈顶元素 */
int get_top()
{
    if(!top){
        printf("Stack is NULL.\n");
        exit(0);
    }
    
    return top->data;
}
/* 括号匹配函数,返回值1匹配,0不匹配 */
int macth_kuohao(char msg[])
{
    int i=0;
    
    for(i=0;i<strlen(msg);i++)
	{
        switch(msg[i]){
            case '{':
            case '[':
            case '(':push(msg[i]);break; /* 遇到'{','[',')'则压栈 */
            case '}':
                if(get_top()=='{'){ /* 取栈首元素比较 */
                    pop();
                    break;
                }
                else
                    return 0;
            case ']':
                if(get_top()=='['){
                    pop();
                    break;
                }
                else
                    return 0;
            case ')':
                if(get_top()=='('){
                    pop();
                    break;
                }
                else
                    return 0;
        }
    }
     if(!top)/* 测试堆栈是否为空 */

        return 1;
    else
        return 0;
   
}

  

/* 打印堆栈 */
void print_stack()
{
    node *p;
    
    p=top;
    if(!p){
        printf("Stack is NULL.\n");
        exit(0);
    }
    while(p){
        printf("%c",p->data);
        p=p->next;
    }
}

int main(void)
{
    char msg[100];
    int i;
    
    printf("input msg:");
    scanf("%s",msg);
    printf("\n%s\n",msg);
    i=macth_kuohao(msg);
    if(i)
        printf("kuohao is right.\n");
    else
        printf("kuohao is not right.\n");
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -