基础实验3-2.4-出栈序列的合法性-编程题

基础实验3-2.4-出栈序列的合法性-编程题

解题代码

#include<stdio.h>
#include<stdlib.h>
typedef enum { false, true } bool;
typedef struct stack* pst;
struct stack {
	int* data;
	int top;
	int cnt;
	int capacity;
};
bool Judge(int M, int N);
bool Check(pst S, int* T, int i);
bool IsEmpty(pst S);
int Peek(pst S);
bool IsFull(pst S);
void Push(pst S);
void Pop(pst S);
int main()
{
	int M;//capacity of stack
	int N;//number of push
	int K;//number of case
	int flag = 1;//adjust outcome
	scanf("%d %d %d", &M, &N, &K);
	while (K--) {
		if (flag) flag = 0;
		else printf("\n");
		if (Judge(M, N)) printf("YES");
		else printf("NO");
	}
	return 0;
}
bool Judge(int M, int N) {
	bool flag = true;
	int* T = (int*)malloc(N * sizeof(int));
	int i;
	for (i = 0; i < N; i++) scanf("%d", &T[i]);
	pst S = (pst)malloc(sizeof(struct stack));
	S->capacity = M;
	S->cnt = 0;
	S->top = -1;
	S->data = malloc(M * sizeof(int));
	for (i = 0; i < N; i++) { if (!Check(S, T, i)) flag = false; }
	return flag;
}
bool Check(pst S,int* T,int i) {
	while (true) {
		if (IsEmpty(S) || Peek(S) < T[i]) {
			if (IsFull(S)) return false;
			else Push(S);
		}
		else if (Peek(S) == T[i]) {
			Pop(S);
			return true;
		}
		else return false;
	}
}
bool IsEmpty(pst S) {
	if (S->top == -1) return true;
	else return false;
}
int Peek(pst S) {
	return S->data[S->top];
}
bool IsFull(pst S) {
	if (S->top == S->capacity - 1) return true;
	else return false;
}
void Push(pst S) {
	S->data[++S->top] = ++S->cnt;
}
void Pop(pst S) {
	S->top--;
}

测试结果

在这里插入图片描述

问题整理

1.注意Check函数。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值