中國大學MOOC-陳越、何欽銘-數據結構-2018春 第二講課後習題第四題 ...
這道題是2013年PAT春季考試真題,考察隊堆棧的基本概念的掌握。在保證輸入正確後,關鍵在於對"Pop"序列的判斷,我用isPopOrder函數進行了判斷,代碼如下:
#include <stdio.h> #include <stdlib.h> #define MaxSize 1001 typedef struct SNode *Stack; struct SNode{ int Data[MaxSize]; int MaxCap; //Maximum capacity of this stack int Top; }; Stack CreateStack(int M) { Stack PtrS; PtrS = (Stack)malloc(sizeof(struct SNode)); PtrS->Top = -1; PtrS->MaxCap = M; return PtrS; } /*堆棧基本操作此處略去*/ int isPopOrder(int *CheckOrder, int M, int N, int K) { int i, ci = 0; Stack S; S = CreateStack(M); for(i = 1; i < N + 1; i++){ Push(i, S); //Push in the order of 1, 2, ..., N while(CheckOrder[ci] == GetTop(S)){ Pop(S); ci++; } } if(GetTop(S) == -1) //堆棧為空 return 1; else return 0; } int main(int argc, char const *argv[]) { int M, N, K; //M is the maximum capacity of the stack; Push N numbers; K sequences to be checked int i, j; int CheckOrder[MaxSize], res[MaxSize]; scanf("%d %d %d", &M, &N, &K); for(i = 0; i < K; i++){ for(j = 0; j < N; j++){ scanf("%d", &CheckOrder[j]); } res[i] = isPopOrder(CheckOrder, M, N, K); } for(i = 0; i < K; i++){ if(res[i]) printf("YES\n"); else printf("NO\n"); } return 0; }
(待更新)