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

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

被折叠的 条评论
为什么被折叠?



