1. 程式人生 > >堆疊--括號匹配檢驗

堆疊--括號匹配檢驗

根據堆疊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;
}