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

02-线性结构4 Pop Sequence

程序员文章站 2022-04-28 09:18:16
中国大学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;
}

(待更新)