码迷,mamicode.com
首页 > 其他好文 > 详细

栈&&括号匹配

时间:2015-05-09 13:25:31      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:   结构   

利用栈的结构性质实现括号匹配

(今天被自己玩死了,‘=‘&&‘==‘小问题坑死人不偿命)

Matbr.h

#ifndef _MATCH_H_
#define _MATCH_H_

#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;

typedef char ElemType;
#define STACK_MAX_SIZE 100

typedef struct Stack
{
	ElemType *base;
	int top;
	int stacksize;
	int capacity;
}Stack;

void InitStack(Stack *stack);
bool isfull(Stack *stack);
bool isempty(Stack *stack);
bool push(Stack *stack,ElemType x);
bool pop(Stack *stack);
ElemType GetTop(Stack *stack);

#endif //_MATCH_H_
Matbr.cpp

#include"Matbr.h"


void InitStack(Stack *stack)
{
	stack->base = (ElemType *)malloc(sizeof(ElemType)*STACK_MAX_SIZE);
	assert(stack->base != NULL);
	stack->top = 0;
	stack->capacity = STACK_MAX_SIZE;
	stack->stacksize = 0;
}

bool isfull(Stack *stack)
{
	return stack->stacksize == stack->capacity;
}

bool isempty(Stack *stack)
{
	return stack->stacksize == 0;
}

bool push(Stack *stack,ElemType x)
{
	if(isfull(stack))
		return false;

	stack->base[stack->top++] = x;
	stack->stacksize++;
	return true;
}

bool pop(Stack *stack)
{
	if(isempty(stack))
		return false;
	stack->base[stack->top--];
	stack->stacksize--;
	return true;
}

ElemType GetTop(Stack *stack)
{
	if(isempty(stack))
	{
		cout<<"栈空!"<<endl;
	}
	return stack->base[stack->top-1];
}


man.cpp

#include"Matbr.h"

void main (void)
{
	Stack st;
	char str[2015];
	InitStack(&st);
	cin>>str;
	int len = strlen(str);
	int i = 0;
	int flag = 1;
	while(i<len)
	{
		if(str[i] == '(' || str[i] == '{' ||str[i] == '[')
			push(&st,str[i]);
		else if(str[i] == ')')
		{
			if(isempty(&st) || GetTop(&st) != '(' )
				flag = 0;
			else
				pop(&st);
		}
		else if(str[i] == ']')
		{
			if(isempty(&st) || GetTop(&st) != '[' )
				flag = 0;
			else
				pop(&st);
		}
		else if(str[i] == '}')
		{
			if(isempty(&st) || GetTop(&st) != '{' )
				flag = 0;
			else
				pop(&st);
		}
		i++;
	}
	if(!isempty(&st))
	{
		flag = 0;
	}	
	if(flag == 1)
		cout<<"Matching brackets(匹配)"<<endl;//匹配
	else
	{
		cout<<"The brackets do not match(不匹配)"<<endl;//不匹配
	}
}

技术分享

栈&&括号匹配

标签:   结构   

原文地址:http://blog.csdn.net/chenmengmengx/article/details/45600347

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!