2007winter

做自己真心想做的事,你就没事了

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

栈的应用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();

}

  

posted on 2012-10-23 11:15  2007winter  阅读(159)  评论(0)    收藏  举报