堆栈--括号匹配检验

根据堆栈LIFO原理,对括号的匹配进行检验:

#include<stdio.h>
#include<stdlib.h>

#define STACK_SIZE     1024
#define TYPE           char

typedef struct {
	TYPE *base;
	TYPE *top;
	int stack_size;
}STACK;

int stack_init(STACK *s)
{
	s->base = malloc(STACK_SIZE * sizeof(TYPE));
	if (s->base == NULL)
	{
		return -1;
	}
	s->top = s->base;
	s->stack_size = STACK_SIZE;

	return 0;
}

void stack_destroy(STACK *s)
{
	free(s->base);
	s->base = s->top = NULL;
	s->stack_size = 0;
}

void stack_clear(STACK *s)
{
	s->top = s->base;
}

int stack_length(STACK *s)
{
	return (s->top - s->base);
}

int stack_empty(STACK *s)
{
	return (s->top == s->base);
}

TYPE stack_top(STACK *s, TYPE *e)
{
	if (stack_length(s) == 0)
	{
		return -1;
	}
	*e = *(s->top - 1);

	return *e;
}

int stack_push(STACK *s, TYPE e)
{
	if (stack_length(s) >= s->stack_size)
	{
		return -1;
	}

	*(s->top++) = e;
	
	return 0;
}

int stack_pop(STACK *s, TYPE *e)
{
	if (stack_length(s) == 0)
	{
		return -1;
	}

	*e = *(--s->top);

	return 0;
}

int main()
{
	STACK *s;
	char symbol, elem;
	FILE *fd;
	
	fd = fopen("symbol", "r");
	if (fd == NULL)
	{
		return -1;
	}
	s = (STACK *)malloc(sizeof(STACK));
	if (s == NULL)
	{
		return -1;
	}
	stack_init(s);
	while(fread(&symbol, sizeof(symbol), 1, fd) == 1)
	{
		if (stack_empty(s))
		{
			if (symbol == '('
				|| symbol == '['
				|| symbol == '{')
			{
				stack_push(s, symbol);
			}
		}
		else
		{
			if ((symbol - stack_top(s, &elem) == 1) 
				|| (symbol - stack_top(s, &elem) == 2)
				|| (symbol - stack_top(s, &elem) == 2))
			{
				stack_pop(s, &symbol);
			}
			else
			{
				if (symbol == '('
					|| symbol == '{'
					|| symbol == '[')
				{
					stack_push(s, symbol);
				}
			}
		}
	}
	if (stack_empty(s))
	{
		printf("correct symbol\n");
	}
	else
	{
		printf("wrong symbol\n");
	}
	
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值