欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-07 20:46:59
...

基础实验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--;
}

测试结果

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

问题整理

1.注意Check函数。