#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define QElemType char
#define maxsize 100
#define Stackinitsize 100
#define Stackincement 10
typedef struct Qnode
{
QElemType data;
struct Qnode* next;
}Qnode,*QueuePtr;
typedef struct Queue{
QueuePtr front;
QueuePtr rear;
}Queue,*LinkQueue;
//有头结点
void InitQueue(LinkQueue q){
q->rear=q->front=(QueuePtr)malloc(sizeof(Qnode));
q->front->next=NULL;
//q->front->data=NULL;
}
void ClearQueue(LinkQueue q){
}
int qisempty(LinkQueue q){
if(q->front==q->rear)return 1;
return 0;
}
void EnQueue(LinkQueue q,QElemType e){
QueuePtr p=(QueuePtr)malloc(sizeof(struct Qnode));
p->next=NULL;
p->data=e;
q->rear->next=p;
q->rear=p;
}
QElemType DeQueue(LinkQueue q){
if(q->rear==q->front)return 0;
QueuePtr p=q->front->next;
QElemType e=p->data;
q->front->next=p->next;
if(q->rear==p)q->rear=q->front;
free(p);
return e;
}
typedef struct
{
char* base;
char* top;
int stacksize;
}Sqstack;
Sqstack Initstack(Sqstack s){
s.base=(char *)malloc(sizeof(char)*Stackinitsize);
if(!s.base)exit(0);
s.top=s.base;
s.stacksize=Stackinitsize;
return s;
}
char Gettop(Sqstack s){
char e;
if(s.base==s.top)
return 0;
e=*(s.top-1);
return e;
}
Sqstack push(Sqstack s,char e){
if(s.top-s.base>=s.stacksize){
s.base=(char *)realloc(s.base,((s.stacksize+Stackincement)*sizeof(char)));
if(!s.base)exit(0);
s.top=s.base+s.stacksize;
s.stacksize+=Stackincement;
}
*(s.top)=e;
s.top++;
//printf("aa");
return s;
}
char e;
Sqstack pop(Sqstack s){
if(s.base==s.top)return s;
e=*(--s.top);
return s;
}
Sqstack clearstack(Sqstack s){
s.base=s.top;
return s;
}
int stackisempty(Sqstack s){
if(s.base==s.top||s.base==NULL)
return 1;
else
return 0;
}
int stackLength(Sqstack s){
int len;
len=s.top-s.base;
return len;
}
void printstack(Sqstack s){
if(s.base==s.top)exit(0);
char* p=s.base;
while(p!=s.top){
printf("%d ",*p);
p++;
}
}
int main(){
Sqstack s1=Initstack(s1);
Sqstack s2=Initstack(s2);
char a[100]={0};
scanf("%s",&a);
int i=strlen(a)-1;
for(;i>=0;){
s1=push(s1,a[i]);
i--;
}
while(!stackisempty(s1)){
char r;
s1=pop(s1);
r=e;
if(r!=')'){
i++;
s2=push(s2,r);
}
else if(r==')'){
LinkQueue q=(Queue*)malloc(sizeof(struct Queue));
InitQueue(q);
char c;
s2=pop(s2);
c=e;
while(e!='('){
EnQueue(q,e);
c=e;
s2=pop(s2);
}
while(q->front->next!=q->rear){
char b;
b=DeQueue(q);
s2=push(s2,c);
s2=push(s2,b);
}
s2=push(s2,c);
}
}
while(!stackisempty(s2)){
char n;
char A[4]="sae";
char B[9]="tsaedsae";
s2=pop(s2);
if(e!='A'&&e!='B'){
s1=push(s1,e);
}
else if(e=='A'){
for(int i=2;i>=0;i--)
s1=push(s1,A[i]);
}
else if(e=='B'){
for(int i=7;i>=0;i--)
s1=push(s1,B[i]);
}
}
while(!stackisempty(s1)){
s1=pop(s1);
printf("%c",e);
}
return 0;
}
*指针需要初始化,注意初始化大小,否则xdoj提示超时!!!
*支持多括号输入:B(ab(xy)f)A
输出:
原理:每遇见处理')'时重置队列q;
有参考。