7-5-Tree Traversals Again-编程题
解题代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Flag = 1;
typedef struct stack* pst;
struct stack {
int* data;
int* flag;
int top;
int capacity;
};
pst CreatStack(int N);
void Handle(pst S);
void Push(pst S);
void Pop(pst S);
void Handle_else(pst S);
int main()
{
int N;
scanf("%d\n", &N);
pst S = CreatStack(N);
int i;
for (i = 0; i < N * 2; i++) Handle(S);
Handle_else(S);
return 0;
}
pst CreatStack(int N) {
pst S = (pst)malloc(sizeof(struct stack));
S->top = -1;
S->capacity = N;
S->data = malloc(N * sizeof(int));
S->flag = malloc(N * sizeof(int));
int i;
for (i = 0; i < N; i++) S->flag[i] = 0;
return S;
}
void Handle(pst S) {
char temp[10];
scanf("%s", &temp);
if (!strcmp(temp,"Push")) Push(S);
else if (!strcmp(temp, "Pop")) Pop(S);
}
void Push(pst S) {
int temp_data;
scanf("%d\n", &temp_data);
S->top++;
S->data[S->top] = temp_data;
S->flag[S->top] = 1;
}
void Pop(pst S) {
char temp;
if(S->flag[S->top+1]!=2) temp = getchar();
if (S->flag[S->top] == 1) S->flag[S->top]=2;
else if (S->flag[S->top] == 2) {
if (Flag) Flag = 0;
else printf(" ");
printf("%d", S->data[S->top]);
S->top--;
Pop(S);
}
}
void Handle_else(pst S) {
while (S->top >= 0) Pop(S);
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/12db796907ae37648328477833917f14.png)
问题整理
1.注意子函数中的flag在控制输出格式失效时,也许要改成全局变量。