输入广义表表示的字符串,str
对于 str[i],设置变量 k = -1
若为‘(’,令 k = 0
若为‘,’,k=1
若为‘)’,栈顶元素出栈
若为字符时
k = -1, 该元素为树的根结点
k = 0, 栈首元素左孩子为str[i],并把str[i]压入栈
k = 1, 栈首元素右孩子为str[i],并把str[i]压入栈
c++也有栈,可以手写,我用的是双端队列模拟栈
//A(B(E(K,L),F),C(D(,H)))
#include <bits/stdc++.h>
using namespace std;
char str[100];
struct node {
char ch;
struct node * lc,*rc;
/* node(char c,node*t)
{
ch = c;
next = t;
}*/
};
node * root;
int num;
void build() {
int n=strlen(str);
deque<node*> q;
while(!q.empty())q.pop_back();
int k=-1;
for(int i=0 ; i<n ; i++) {
if(str[i] == '(') {
k = 0;
}
else if(str[i] == ',') {
k = 1;
q.pop_back();
}
else if(str[i] == ')') {
q.pop_back();
}
else {
num++;
node *tmp = new node{str[i]};
if( k == -1 )
{
q.push_back(tmp);
root = q.back();//栈顶元素
}
else if(k == 0)
{
q.back()->lc = tmp;
q.push_back(tmp);
}
else if(k == 1)
{
q.back()->rc = tmp;
q.push_back(tmp);
}
}
}
}
void print(node *p)
{
queue<node*>q;
while(!q.empty())q.pop();
q.push(p);
while(!q.empty())
{
node *t = q.front();
q.pop();
printf("%c ",t->ch);
if(t->lc)q.push(t->lc);
if(t->rc)q.push(t->rc);
}
}
int main() {
scanf("%s",str);
num = 0;
build();
print(root);
printf("\n%d",num);
return 0;
}