问题描述:给定一个栈,最多可存放M个元素,现要将N个数(1-N),随机入栈、出栈,入栈顺序由小到大,判断一个给定的序列是否合法。
思路:要依次判断序列中的每一个数,判定为不合法的情况有:
上述两种情况发生时直接判断不合法,其他情况:
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> void Judge(int M, int N); int main() { int M, N, K; if(scanf("%d %d %d",&M,&N,&K)==3){} for (int i = 0;i < K;i++) Judge(M, N); return 0; } void Judge(int M, int N) { int* stack = (int*)malloc(sizeof(int) * (M+1));//用数组模拟一个栈 int top = 0; int* flag = (int*)malloc(sizeof(int) * (N+1)); int* number = (int*)malloc(sizeof(int) * (N + 1)); memset(flag, 0, sizeof(int) * (N + 1)); int i, j, k; for (i = 1;i <= N;i++) { if(scanf("%d",&number[i])==1){} } for (i = 1;i <= N;i++) { if (stack[top] > number[i]) { printf("NO\n"); return; } if (stack[top] == number[i]) { flag[number[i]] = 2; top--; continue; } for (k = 1;k < number[i];k++) { if (flag[k] == 0) { top++; if (top > M) { printf("NO\n"); return; } flag[k] = 1; stack[top] = k; } } if (top + 1 > M) { printf("NO\n"); return; } flag[number[i]] = 2; } printf("YES\n"); free(stack); return; }
原文:https://www.cnblogs.com/yaotong0830/p/14253837.html