用三个栈纯模拟解题,用的是数据结构栈表达式求值括号匹配的思想,用法不是那么规范
三个栈,S1,S2,S3,S1存字符串,S2存数字(就是个数组),S3存括号数(就是个变量) 若读入前括号,读入一个数字存入S2,S1跳到下一层开始存;读入后括号,按S2栈顶数字对S1栈顶加倍后与S1栈顶下一个字符串合并,以此类推,直到读入'\n' 代码如下
#include <stdio.h>
#include <string.h>
#define MAXSIZE 20010
typedef struct
{
int base;
int top;
char cha[MAXSIZE][2000];
}SqStackA;
void InitStack(SqStackA &S)
{
S.base=S.top=1;
}
typedef struct
{
int num[10000];
int k;
}SqStackB;
void Add(int n,SqStackA &S)
{
char temp[100];
strcpy(temp,S.cha[S.top]);
while(n>1)
{
n--;
strcat(S.cha[S.top],temp);
}
}
int main()
{
SqStackA S;
InitStack(S);
SqStackB Snum;Snum.k=0;
int Scount=0;
while(1)
{
char k;
scanf("%c",&k);
if(k=='\n') break;
if(k=='[')
{
Scount++;
scanf("%d",&Snum.num[++Snum.k]);
S.top++;
strcpy(S.cha[S.top],"\0");
}
else if(k==']')
{
Scount--;
int t=Snum.num[Snum.k]; //弹出S3
Add(t,S); //S1加倍,弹出S2
Snum.k--;
strcat(S.cha[S.top-1],S.cha[S.top]); //S1上下结合
strcpy(S.cha[S.top],"\0");
S.top--; //弹出S1
}
else
{
char ttt[3]={k,'\0'};
strcat(S.cha[S.top],ttt);
}
}
printf("%s",S.cha[S.base]);
return 0;
}