使用数组实现堆栈

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
#define OK    1
#define ERROR 0
typedef int Status;
typedef int SElemType;
struct SqStack
{
    SElemType data[MAXSIZE];//数组实现堆栈
    int top;                //栈元素序号
};


Status push(struct SqStack *S, SElemType value)
{
    /*栈满*/
    if(S->top == MAXSIZE - 1)
    {
        return ERROR;
    }
    S->top++;
    S->data[S->top] = value;
    return OK;
}

Status pop(struct SqStack *S, SElemType *value)
{
    /*栈空*/
    if(S->top == -1)
        return ERROR;
    *value = S->data[S->top];
    S->top--;
    return OK;
}

int is_full(struct SqStack *S)
{
    return S->top == MAXSIZE- 1;
}

int is_empty(struct SqStack *S)
{
    return S->top == -1;
}

int main(void)
{
    struct SqStack *stack = (struct SqStack*)malloc(sizeof(struct SqStack));
    int i = 0;
    int value;
    stack->top = -1;//这句话很重要,不然会出错
    for(i=0; i<=10; i++)
    {
        if(is_full(stack))
        {
            printf("stack is full\n");
            break;
        }
        push(stack, i);
        printf("top is %d\n", stack->data[stack->top]);
    }

    for(i=0; i<=10; i++)
    {
        if(is_empty(stack))
        {
            printf("stack is empty\n");
            break;
        }
        pop(stack, &value);
        printf("%d pop\n", value);
    }
    return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
#define OK    1
#define ERROR 0
typedef int Status;
typedef int SElemType;
struct SqStack
{
    SElemType data[MAXSIZE];//数组实现堆栈
    int top;                //栈元素序号
};


Status push(struct SqStack *S, SElemType value)
{
    /*栈满*/
    if(S->top == MAXSIZE - 1)
    {
        return ERROR;
    }
    S->top++;
    S->data[S->top] = value;
    return OK;
}

Status pop(struct SqStack *S, SElemType *value)
{
    /*栈空*/
    if(S->top == -1)
        return ERROR;
    *value = S->data[S->top];
    S->top--;
    return OK;
}

int is_full(struct SqStack *S)
{
    return S->top == MAXSIZE- 1;
}

int is_empty(struct SqStack *S)
{
    return S->top == -1;
}

int main(void)
{
    struct SqStack *stack = (struct SqStack*)malloc(sizeof(struct SqStack));
    int i = 0;
    int value;
    stack->top = -1;//这句话很重要,不然会出错
    for(i=0; i<=10; i++)
    {
        if(is_full(stack))
        {
            printf("stack is full\n");
            break;
        }
        push(stack, i);
        printf("top is %d\n", stack->data[stack->top]);
    }

    for(i=0; i<=10; i++)
    {
        if(is_empty(stack))
        {
            printf("stack is empty\n");
            break;
        }
        pop(stack, &value);
        printf("%d pop\n", value);
    }
    return 0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38044916/article/details/77970454
文章标签:
个人分类: 数据结构与算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭