括号匹配问题 栈的应用 C语言实现

本文介绍了一种使用栈实现括号匹配的经典算法。通过遍历输入字符串,利用栈来存储左括号,并与右括号进行匹配。文章提供了完整的源代码实现,包括栈的基本操作如压栈、弹栈等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

括号匹配问题是栈的一个经典应用。程序基本 思路是这样的:遍历字符串,如果遇到左括号就入栈,如果遇到右括号就取栈顶元素,然后比较是否匹配,如果匹配就出栈删除相匹配的括号,如果不匹配就说明括号匹配失败。遍历完成后看栈中是否还有未匹配的括号,如果有就说明括号匹配失败,如果是空栈,就说明括号匹配成功。

程序清单:CharStack.h          BracketMatch.c

BracketMatch.c 

/* BracketMatch.c */
/* Coding by nyzhl */

#include 
<stdio.h>
#include 
"CharStack.h"

#define TRUE 1
#define FALSE 0

int Match(char a, char b) {
    
if(a=='(' && b==')')
        
return TRUE;
    
if(a=='[' && b==']')
        
return TRUE;
    
if(a=='{' && b=='}')
        
return TRUE;
    
return FALSE;
}


int BracketMatch(char *str) {
    LinkStack top;
    top 
= (LinkStack)malloc(sizeof(StackNode));
    InitStack(top);
    
int i =0;
    
while(str[i]!='

 

CharStack.h

/* CharStack.h */
/* Coding by nyzhl */
#include 
<stdlib.h>

#define TRUE 1
#define FALSE 0
#define NULL 0

typedef 
char ElementType;
typedef 
struct node {
    ElementType data;
    
struct node *next;
}
StackNode, *LinkStack;

void InitStack(LinkStack top) {
    top
->next = NULL;
}


int IsEmpty(LinkStack top) {
    
if(top->next == NULL) return TRUE;
    
return FALSE;
}


int Push(LinkStack top, ElementType element) {
    StackNode 
*temp;
    temp 
= (StackNode *)malloc(sizeof(StackNode));
    
if(temp == NULL) return FALSE;
    temp
->data = element;
    temp
->next = top->next;
    top
->next = temp;
    
return TRUE;
}


int Pop(LinkStack top, ElementType *element) {
    
if(IsEmpty(top)) return FALSE;
    StackNode 
*temp = top->next;
    
*element = temp->data;
    top
->next = temp->next;
    free(temp);
    
return TRUE;
}


void GetTop(LinkStack top, ElementType *element) {
    
*element = top->next->data;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值