习题3.14 另类堆栈 (15分)

题目

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>

#define ERROR -1
typedef int ElementType;
typedef enum { push, pop, end } Operation;
typedef enum { false, true } bool;
typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode {
    ElementType *Data;  /* 存储元素的数组 */
    Position Top;       /* 栈顶指针       */
    int MaxSize;        /* 堆栈最大容量   */
};
typedef PtrToSNode Stack;

Stack CreateStack( int MaxSize )
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    S->Top = 0;
    S->MaxSize = MaxSize;
    return S;
}

bool Push( Stack S, ElementType X );
ElementType Pop( Stack S );

int main()
{
    int x=2,n,maxsize=4;
    int done = 0;
    Stack S = CreateStack(maxsize);
    while(!done){
        scanf("%d",&x);
    switch (x)
    {
    case 1:
        scanf("%d",&n);
        Push(S,n);
        break;
    case 2:
        n = Pop(S);
        if(n!=-1)printf("%d is out\n",n);
    break;
    default:
        done = 1;
        break;
    }
    }
     return 0;
}

bool Push( Stack S, ElementType X )
{
    if(S->Top == S->MaxSize)
    {
        printf("Stack Full\n"); return false;
    }
    S->Data[S->Top++] = X;
    return true;
}
ElementType Pop( Stack S )
{
    int X;
    if(S->Top == 0)
    {
        printf("Stack Empty\n"); return ERROR;
    }
    
    X = X = S->Data[--S->Top];
    return X;
}

核心代码

bool Push( Stack S, ElementType X )
{
    if(S->Top == S->MaxSize)
    {
        printf("Stack Full\n"); return false;
    }
    S->Data[S->Top++] = X;
    
    return true;
}
ElementType Pop( Stack S )
{
    int X;
    if(S->Top == 0)
    {
        printf("Stack Empty\n"); return ERROR;
    }
    
    X = S->Data[--S->Top];
    return X;
}

在这里插入图片描述

可以使用*(S->Data+S->Top) 也可以使用S-Data[S->Top]

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页