栈的应用2:检查括号匹配

栈的应用2:

#include<iostream>
#include<malloc.h>
#include<conio.h>
#include<stdio.h>

using namespace std;

#define STACK_INT_SIZE 100
#define STACEINCREMENT 10
typedef int SElemType;
typedef struct SqStack
{
	SElemType *base;
	SElemType *top;
	int stacksize;
}SqStack;

int InitStack(SqStack &s)
{
	s.base=(SElemType *)malloc(STACK_INT_SIZE*sizeof(SElemType));
	if(!s.base)
	{
		cout<<"overflow!"<<endl;
		return 0;
	}
	s.top=s.base;
	s.stacksize=STACK_INT_SIZE;
	cout<<"Success to constructe an empty stack!"<<endl;

	return 1;
}


int push(SqStack &s,SElemType e)
{
	if(s.top-s.base>s.stacksize)
	{
		s.base=(SElemType *)realloc(s.base,(s.stacksize+STACEINCREMENT*sizeof(SElemType)));
		if(!s.base)
		{
			cout<<"Failure!"<<endl;
			return 0;
		}
		s.top=s.base+s.stacksize;
		s.stacksize+=STACEINCREMENT;

	}

	*s.top++=e;
	return 1;

}

int pop(SqStack &s, SElemType &e)
{
	if(s.top==s.base)
	{
		cout<<"underflow!"<<endl;
		return 0;
	}

	e=*--s.top;
	return 1;

}


int StackEmpty(SqStack &s)
{
	if(s.top==s.base)
		return 1;
	else 
		return 0;
}

SElemType GetTop(SqStack S)
{
	if(S.base==S.top)
	{
		cout<<"error! the stack has been empty!"<<endl;
		exit(0);
	}
	else
		return (*(S.top-1));
}


int check()
{
	SqStack S;
	char ch;
	SElemType temp;
	int CorrectInput;
	InitStack(S);
	push(S,'#');
	cout<<"please input the character:"<<endl;
	ch=getchar();
	CorrectInput = 1;
	while(ch!='\n'&&CorrectInput)
	{
		if(ch=='(')
			push(S,ch);
		if(ch==')')
		{
			if(GetTop(S)=='#')
				CorrectInput=0;
			else 
				pop(S,temp);
		}
		ch=getchar();
			
	}

	if(GetTop(S)!='#')
		CorrectInput=0;
	if(!CorrectInput)
	{
		cout<<"Error! the Left Round bracket does not match the Right one. "<<endl;
		return 0;
	}
	else
	{
		cout<<"OK...! the Left Round bracket does match the Right one. "<<endl;
		return 1;
	}

}


void main()
{
	cout<<"check.cpp"<<endl<<"========================"<<endl<<endl;

	check();
	getch();

}

  

转载于:https://www.cnblogs.com/2007winter/archive/2012/10/23/2735165.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值