数据结构-顺序栈

#include <stdio.h>
#include <stdlib.h>
//顺序栈,用数组
//数组的话没有链表那么花里胡哨
//初始化、入栈、出栈、遍历

#define MAX_SIZE 10
typedef int DataType;
typedef struct
{
    DataType data[MAX_SIZE];
    int top;
} SeqStack;

void Initial(SeqStack* s);
void push(SeqStack* s, DataType x);
DataType pull(SeqStack* s);
void print(SeqStack* s);

int main()
{
    SeqStack s;
    Initial(&s);
    for (int i = 0; i < 4; i++)
    {
        push(&s, i);
    }

    DataType x;
    for (int i = 0; i < 4; i++)
    {
        x = pull(&s);
        printf("%d", x);
    }
    system("pause");
    return 0;
}

//初始化顺序栈
void Initial(SeqStack* s)
{
    s->top = -1;
}

void push(SeqStack* s, DataType x)
{
    //入栈要保证此时,栈内元素不满
    if (s->top == MAX_SIZE - 1)
    {
        printf("%d", x);
        printf("元素已满!");
    }
    else
    {
        //++s->top;
        //->是第一级顺序
        s->data[++s->top] = x;
    }
}

DataType pull(SeqStack* s)
{
    DataType x;
    //出栈要保证此时,栈内元素不为空
    if (s->top == -1)
    {
        printf("栈内元素为控空,无法遍历!");
    }
    else
    {
        x = s->data[s->top--];
        //s->top--;
    }
    return x;
}

void print(SeqStack* s)
{
    //遍历元素要判断不为空
    if (s->top == -1)
    {
        printf("元素为空!无法遍历。");
    }
    else
    {
        while (s->top != -1)
        {
            printf("%d", s->data[s->top--]);
            //s->top--;
        }
    }
    return;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值