用栈实现括号匹配

构造栈函数并用栈实现括号匹配

以下代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//建立一个栈,用栈求出二进制转十进制,转八进制,销毁,清空,Push,Pop
//用栈来求逆波兰算法(用字符来转成双精度变量),用栈来检验括号是否正确
//建立一个链表栈,并具有插入,删除操作
#define INITNUM 20
#define INCREASENUM 5
typedef  char elem;
typedef struct Stack {
	elem* top;
	elem*base;
	int StackSize;
}sqStack;
void InitStack(sqStack*s) {
	s->base = (elem*)malloc(INITNUM*sizeof(elem));
	s->top = s->base;
	s->StackSize = INITNUM;
}
void Push(sqStack*s,elem e) {
	//添加数据时,当数据的大小超过预订值时,需要对整个链表的存储空间进行更改
	if (s->top - s->base >= s->StackSize) {
		s->base = (elem*)realloc(s->base, (s->StackSize + INCREASENUM) * sizeof(elem));
		s->top = s->base + s->StackSize;
		s->StackSize = s->StackSize + INCREASENUM;
		//StackSize发生改变
	}
	*(s->top) = e;
	s->top++;//把s的栈顶上移一位
}
//出栈,并获得出栈的数据
void Pop(sqStack*s, elem*e) {
	if (s->top == s->base)
		return;
	else {
		*e = *(--s->top);//对原来的e值进行改变
		//s->top下面的值才是要出栈的数据
	}
}
void ClearStack(sqStack*s) {
	s->top = s->base;//清空列表
}
int StackLen(sqStack*s) {
	return s->top - s->base;
	//获取当前链表长度
}
void DestroyStack(sqStack*s) {
	int len = INITNUM;
	for (int i = 0; i < len; i++) {
		free(s->base);
		s->base++;
		//其实就是把栈置空
	}
	s->base = s->top = 0;
	s->StackSize = 0;
}


//判断括号是否匹配的函数
int IsAlign(sqStack*s) {
	char c,temp=0;
	printf("请输入一系列括号,以回车键结束:");
	scanf("%c", &c);
	//scanf()输入字符时,键盘的缓冲空间为1,即读即存
	//而输入int型变量时,其空间大小为4个字节,需要回车后才能存储
	while (c != '\n') {
		switch (c)
		{
		case '{':
			Push(s, c);
			break;
		case '[':
			Push(s, c);
			break;
		case '(':
			Push(s, c);
			break;
		case ')':
			Pop(s, &temp);//把当时栈里的数出栈
			if (temp == '(')
				break;
			else
				return 0;
		case ']':
			Pop(s, &temp);
			if (temp == '[')
				break;
			else
				return 0;
		case '}':
			Pop(s, &temp);
			if (temp == '{')
				break;
			else
				return 0;
		default:
			break;
		}
		scanf("%c", &c);
	}
	if ((s->top != s->base) || !temp)//当没输入字符或只输入了半截括号时返回值为0
		return 0;
	return 1;
}
int main() {
	sqStack s;
	InitStack(&s);//一定要先进行初始化,否则base没有赋值空间
	if (IsAlign(&s))
		printf("匹配成功!\n");
	else
		printf("匹配失败!\n");
	return 0;
}

阅读更多

没有更多推荐了,返回首页