03-树3-Tree Traversals Again-编程题

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的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值