栈~顺序存储结构~基本操作

#include<stdio.h>
#define Maxsize 1024

typedef struct {                    //定义结构体
   int data[Maxsize];
   int top;
}Stack,*Stackp;

Stackp stack_creat(Stackp s)           //创建栈
{
    int x,i=0;
    printf("请输入第%d个元素:",i+1);
    scanf("%d",&x);
    while(x != -1)
    {
       s->top=i;
       s->data[i++]=x;
       printf("请输入第%d个元素:",i+1);
       scanf("%d",&x);
    }
   return s;
}

void stack_print(Stackp s)       //打印栈
{
    int i;
    for(i = 0; i<=s->top; i++ )
    {
        printf("%d ",s->data[i]);
    }
    printf("\n");
}

int Stack_length(Stackp s)         //求栈长
{
     int n;
     n = s->top + 1;
     return n;
}

void stackP_empty(Stackp s)        //设置空栈
{
      s->top=-1;
}

int stack_isEmpty(Stackp s)            //判断是否为空栈
{
    int flag;
    if(s->top<0)
        return 1;
    else
        return 0;
}

Stackp stack_push(Stackp s,int x)        //元素入栈
{
    if(s->top>=Maxsize-1)
       {
           printf("overflow!!!\n");
           return s;
       }
    else
       {
         ++s->top;
         s->data[s->top]=x;
         return s;
       }
}

int  Stack_pop(Stackp s)       //元素出栈
{
    if(stack_isEmpty(s))
    {
        printf("underflow!!!\n");
        return NULL;
    }
    else
    {
        return s->data[s->top--];
    }
}

int Stack_get(Stackp s)            //取栈底元素
{
    if(stack_isEmpty(s))
    {
        printf("underflow!!!\n");
        return NULL;
    }
    else
    {
        return s->data[s->top];
    }
}

int main()
{
    Stackp stack_creat(Stackp s);
    void stackP_empty(Stackp s);              //设置空栈
    int stack_isEmpty(Stackp s);              //判断是否为空栈
    Stackp stack_push(Stackp s,int x);        //元素入栈
    int  Stack_pop(Stackp s);                 //元素出栈
    int Stack_get(Stackp s);                  //获取栈顶元素

    int x;
    Stackp s;
    s=(Stackp)malloc(sizeof(Stack));          //开辟结点

    s = stack_creat(s);
    stack_print(s);

    printf("请输入需要入栈的元素:");
    scanf("%d",&x);
    s=stack_push(s,x);
    stack_print(s);

    Stack_pop(s);                          //元素出栈
    stack_print(s);

    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值