7-5-Tree Traversals Again-编程题

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;//n of node of stack
	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);
	//printf("\n\t1%s1\n", 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);
}

测试结果

在这里插入图片描述

问题整理

1.注意子函数中的flag在控制输出格式失效时,也许要改成全局变量。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值