顺序栈

栈的顺序存储称顺序栈,图示:
这里写图片描述

.h文件

//顺序栈 

#define MaxSize  5 
#define ElemType int

typedef struct 
{
    ElemType data[MaxSize];
    ElemType top;    //栈顶指针 
}Stack;

//函数声明 
Stack InitStack();  //初始化一个栈(顺序栈为新建,与链栈不同) 
bool StackEmpty(Stack *p) ;  //判断栈空 
void  Push(Stack *p,ElemType x);  //进栈
ElemType Pop(Stack *p);  //出栈 
ElemType  GetTop(Stack *p);  //读栈顶元素
void ClearStack(Stack *p); //销毁栈 
 void PrintStack(Stack *p); //打印栈 

.c文件

//  顺序栈 

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

 int main()
 {
    int n=1;
    Stack s;
    s=InitStack();
    PrintStack(&s);



    while(n!=0)
    {
         printf("\t\t/\n");
         printf("\t\tinput your choice \n");
         printf("\t\t1.push stack \n");
         printf("\t\t2.pop stack \n");
         printf("\t\t/\n");
         scanf("%d",&n);
        switch(n)
        {
            int m;
            case 1: printf("1.input the elem you want to push\n");
                    scanf("%d",&m);
               Push(&s,m); 
               PrintStack(&s);
                break;
            case 2: int p=Pop(&s);
                printf("pop the numble: %d \n",p);
                break;
            default:
                break;
        }
    }

    return 0;
 }


 Stack InitStack()  //初始化一个栈
 {
    Stack s;
    s.top =0;
    int n,m;
    printf("input the numble of elem you want to add\n"); 
    scanf("%d",&n);
    printf("input the  elem \n"); 
    for(int i=0;i<n;i++)
    {
        scanf("%d",&m); 
        s.data[i]=m;
     }
     s.top=n-1;
     return s;
 } 

 bool StackEmpty(Stack *p)   //判断栈空 
 {
    if(p->top == -1)
    {
        return true; 
     }else {
        return false; 
    }
 }


 void PrintStack(Stack *p) //打印栈 
  {
    int length = p->top;
    printf("printf\n"); 
    for(int i=0;i<=length;i++)
    {
        printf("%d ",p->data[i]); 
      }
        printf("\n"); 
  }

  void  Push(Stack *p,ElemType x) //进栈
  {
    int top =p->top;
    //判断栈是否为满
      if(top!=MaxSize-1)
      {
        p->data[top+1]=x;
        p->top++;
    } else{
      printf("the Stack is full!\n"); 
      }
  }

   ElemType Pop(Stack *p)  //出栈 
  {
    //判断栈是否为空 
    if(StackEmpty(p)==true)
    {
        printf("the stack is empty!\n");
        return NULL;
      }else     return p->data[p->top--];

  } 
ElemType  GetTop(Stack *p)  //读栈顶元素
{
    //判断栈是否为空 
    if(StackEmpty(p)==true)
    {
        printf("the stack is empty!\n");
        return NULL;
      }else     return p->data[p->top];
}
//void ClearStack(Stack *p); //销毁栈 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值