03-树3-Tree Traversals Again-编程题
解题代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXN 30
int cnt = 1;
typedef struct stack* pst;
struct stack {
int* data;
int top;
int capacity;
int* flag;
};
pst CreatStack(int N);
void Push(pst S);
void ExPop(pst S);
int main() {
int N;
scanf("%d", &N);
pst S = CreatStack(N);
int i;
char in[10];
int check;
for (i = 0; i < N * 2; i++) {
scanf("\n%s", &in);
check = strcmp(in, "Push");
if (!check) Push(S);
else ExPop(S);
}
if (S->top != -1) ExPop(S);
return 0;
}
pst CreatStack(int N) {
pst S = (pst)malloc(sizeof(struct stack));
S->top = -1;
S->capacity = N;
S->data = malloc(MAXN * sizeof(int));
S->flag = malloc(MAXN * sizeof(int));
return S;
}
void Push(pst S) {
int x;
scanf("%d", &x);
S->data[++S->top] = x;
S->flag[S->top] = 1;
}
void ExPop(pst S) {
if (S->top == -1) return;
if (S->flag[S->top] == 1) S->flag[S->top] = 2;
else if (S->flag[S->top] == 2) {
if (cnt) cnt = 0;
else printf(" ");
printf("%d", S->data[S->top--]);
ExPop(S);
}
}
测试结果
问题整理
1.记得把最后剩下的值也输出掉。
2.注意ExPop的逻辑。