C语言 栈的基本操作-【栈顶、栈底 双指针】【初始化栈、出栈、入栈、栈是否为空】

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

#include <iostream>

using namespace std;

#define SElemType int
//#define stackSize 23
#define Status int
#define STACK_INIT_SIZE 23
#define OVERFLOW -1
#define ERROR -1
#define OK 1

typedef struct
{
    SElemType *base; //栈底指针
    SElemType *top;  //栈顶指针
    int stackSize;   //栈的最大容量
} SqStack;

// 初始化栈
Status InitStack(SqStack &S)
{
    S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
    if (!S.base)
    {
        cout << "分配内存失败!";
        exit(OVERFLOW);
    }
    S.top = S.base;
    S.stackSize = STACK_INIT_SIZE;
    cout << "初始化栈成功!" << endl;
    return OK;
}

// 入栈
Status Push(SqStack &S, SElemType e)
{
    if (S.top - S.base >= S.stackSize)
    { // 如果空间不够,追加空间
        S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
        if (!S.base)
            exit(OVERFLOW);
    }
    *S.top++ = e; //先算 *S.top=e; 再 S.top++;
    return OK;
}

// 出栈
Status Pop(SqStack &S, SElemType e)
{
    if (S.top == S.base)
    {
        return ERROR;
    }
    e = *--S.top; //先自减 再赋值
    return OK;
}

// 判断栈是否为空
Status isEmpty(SqStack S)
{
    if (S.top == S.base)
    {
        printf("栈空!\n");
        return ERROR;
    }
    else
    {
        printf("栈非空!\n");
        return OK;
    }
}

int main()
{
    SqStack sq;
    cout << "未初始化,栈sq的空间为: " << sq.stackSize << endl;
    InitStack(sq);
    cout << "初始化后栈s的空间为: " << sq.stackSize << endl;
    printf("%d\n", isEmpty(sq));
    //cout << "初始化后栈s的空间为: " << sq.stackSize << endl;
    //printf("%d", sq.base);
    //printf("%d", sq.top);
    Push(sq, 1);
    printf("%d\n", Push(sq, 1));
    Push(sq, 2);
    Push(sq, 3);
    Push(sq, 4);

    printf("%d\n", isEmpty(sq));
    
    Pop(sq, 1);
    Pop(sq, 1);
    Pop(sq, 2);
    Pop(sq, 3);
    Pop(sq, 4);
    printf("%d\n", isEmpty(sq));
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44949135/article/details/104867484