求助
  • 板块P1241 括号序列
  • 楼主yxsl
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/3/12 23:50
  • 上次更新2023/10/23 21:42:10
查看原帖
求助
802842
yxsl楼主2023/3/12 23:50
#include<stdio.h>
#include<stdlib.h>
#define OVERFLOW -2
#define ERROR 0
#define OK 1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char SElemType;
typedef char Status;
typedef struct
{
	SElemType *base;
	SElemType *top;
	int stacksize;
}SqStack;
Status Initstack(SqStack &S);
Status DestroyStack(SqStack &S);
Status ClearStack(SqStack &S); 
Status StackEmpty(SqStack S);
int StackLength(SqStack S);
Status GetTop(SqStack S,SElemType &e);
Status Push(SqStack &S,SElemType e);
Status Pop(SqStack &S,SElemType &e);
Status StackTraverse(SqStack S,Status(*visit)());

Status Initstack(SqStack &S)
{
	S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
	if(!S.base)exit(OVERFLOW);
	S.top=S.base;
	S.stacksize=STACK_INIT_SIZE;
	return OK;
}

Status GetTop(SqStack S,SElemType &e)
{
	if(S.top==S.base)return ERROR;
	else e=*(S.top-1);
	return OK;
}

Status Push(SqStack &S,SElemType e)
{
	if(S.top-S.base>=S.stacksize)
	{
		S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
		if(!S.base)exit(OVERFLOW);
		S.top=S.base+S.stacksize;
		S.stacksize+=STACKINCREMENT;
	}
	*S.top++=e;
	return OK;
}

Status Pop(SqStack &S,SElemType &e)
{
	if(S.base==S.top)return ERROR;
	else e=*--S.top;
	return OK;
}
int main()
{
	char ch;
	SqStack S;
	Initstack(S);
	do
	{
		scanf("%c",&ch);
		if(ch==' ')continue;
		if(ch==10)break;
		if(ch=='('||ch=='[')
		{
			Push(S,ch);
		}
		if(ch==')'||ch==']')
		{
			char e;
			GetTop(S,e);
			if( ch==')'&&e=='(' )
			{
				Pop(S,e);
				printf("()");
			}
			else
			{
				if( ch==']'&&e=='[' )
				{
					Pop(S,e);
					printf("[]");
				}
				else Push(S,ch);
			}

		}
	}while(1);
	
	while(S.top-S.base>0)
	{
		char e;
		Pop(S,e);
		if(e=='('||e==')')printf("()");
		else printf("[]");
	}
	
return 0;	
} 

2023/3/12 23:50
加载中...