1. 程式人生 > >資料結構--括號匹配檢驗

資料結構--括號匹配檢驗

//本程式用於學習資料結構中的順序棧
//除錯環境 C-Free 5.0 
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
typedef struct
{
	int *base;  //棧底指標 
	int *top;   //棧頂指標 
	int stacksize;
}SqStack;

void InitStack(SqStack*s)
{
	s->base = (int *)malloc(MAXSIZE*sizeof(int));//分配記憶體空間  100*sizeof(int) 
	if (!s->base)    
	{
		return;   //棧空(分配失敗) 
	}
	s->top = s->base;     
	s->stacksize = MAXSIZE; 
}
void push(SqStack *s, char x)  //元素進棧 
{
	if (s->top-s->base==s->stacksize)   //棧滿 
	{
		return;
	}
	*s->top++ = x;  
}
char GetTop(SqStack *s)   //取棧棧頂元素 
{
	if (s->top != s->base)
	{
		return*(s->top-1);      
	}

}
char pop(SqStack *s)    //元素出棧 
{
	if (s->top == s->base)
	{
		return' '; 
	}
	char e;
	e = *--s->top;
	return e;
}
int Maching()
{
	SqStack ss;     //宣告一個結構體 
	SqStack *s = &ss;  //指向結構體的指標 
	InitStack(s);   //初始化棧 
	int flag = 1;
	printf("請輸入符號");
	char ch = getchar();
	while (ch != '#'&&flag)
	{
		switch(ch)
		{
			//char aa;
			//char bb;
			case '[':
			case '(':
					push(s, ch);  //壓入棧 
					break;
				case ')':
				    //aa=GetTop(s);
					if (!(s->top == s->base) && GetTop(s) == '(')
					{
						pop(s);  //出棧 
					}
					else
					{
						flag = 0;
					}
					break;
				case ']':
				    //bb=GetTop(s);
					if (!(s->top == s->base) &&GetTop(s) == '[')
					{
						pop(s);  //出棧 

					}
					else
					{
						flag = 0;
					}
					break;
		}
		ch = getchar();	
	}
	if (s->top == s->base)
		{
			return 1;                    
		}
		else
		{
			return 0;
		}
}

void main()
{
	int n; 
	n=Maching();
	if(n)
	{
		printf("匹配成功\n"); 
	}
	else
	{
		printf("匹配失敗\n");
	}
}