2023-03-30-栈Stack的基本操作

C++:

//栈stack


#include <stdio.h>
#include <stdbool.h>

#define MAXSIZE 100

typedef struct
{
    int data[MAXSIZE]; //数据
    int top;   //栈顶指针,初始为-1
}SqStack;

void initStack(SqStack &S)//初始化栈
{
    S.top=-1;//将栈顶指针设置为-1,所以每次top都指向最后一个元素在数组中的下标,而不是最后一个元素的下一个位置
}

bool StackEmpty(SqStack &S)//判断栈是否为空
{
    if(S.top==-1)//判断栈顶指针是否为-1
    {
        return true;//如果是就返回true
    }
    else{
        return false;
    }
}

bool Push(SqStack &S,int value)//进栈
{
    if(S.top==MAXSIZE-1)//top为0时即指向data[0],数组的最大长度为MAXSIZE-1,所以top也是
    {
        return false;
    }
    else{
        S.top++;
        S.data[S.top] = value;
        return true;
    }
}

bool Pop(SqStack &S,int *e)//出栈,并获取出栈元素的值
{
    if(S.top==-1)
    {
        return false;
    }
    else{
        *e=S.data[S.top];
        S.top--;
        return true;
    }
}

bool GetTop(SqStack &S,int *e)//读栈顶元素
{
    if(S.top==-1)
    {
        return false;
    }
    else
    {
        *e=S.data[S.top];//将栈顶元素传给e
        return true;
    }
}

int main()
{
    SqStack S;
    initStack(S);
    printf("%d\n",S.top);
    int x;
    for(int i=0;i<5;i++)
    {
        scanf("%d",&x);
        Push(S,x);
    }
    for(int j=0;j<=S.top;j++)
    {
        printf("%d ",S.data[j]);
    }
    int *e;
    int a=0;
    e=&a;//对指针进行初始化,避免出现野指针
    GetTop(S,e);
    printf("TOP: %d\n",*e);
    Pop(S,e);
    printf("Pop_value: %d \n",*e);
    //以下为错误代码,为什么添加了下列代码之后程序就跑不起来了?
    // for(int pp=0;pp<=(S->top);pp++)
    // {
    //     printf("%d",S->data[pp]);
    // }
    return 0;
}

 

posted @ 2023-03-30 20:32  正方形的被子  阅读(32)  评论(0)    收藏  举报