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

#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;
}

猜你喜欢

转载自blog.csdn.net/mycsdn_xm/article/details/80717743
今日推荐