堆C数组实现

堆栈是一个最后出来该数据结构.

栈的基本操作包含:入栈,出栈,初始化栈,清空栈,遍历栈.


C代码例如以下:

#include <stdio.h>

#define MaxSize 20
typedef int ElemType;


typedef struct stack
{
    ElemType Data[MaxSize];
    int top;
}Stack;

//初始化栈
void InitStack(Stack *S)
{
    S->top=-1;
}

//入栈
void PushStackValue(Stack *S)
{
    printf("Input the Value of stack member:\n(0-exit)\n");
    int value;
    printf("Please input the 1st value of stack:\n");
    scanf("%d",&value);
    S->Data[++S->top]=value;
    while(value)
    {
        S->top++;
        printf("Please input the %dst value of stack:\n",S->top+1);
        scanf("%d",&value);
        S->Data[S->top]=value;
    }
}

//出栈
void PopStackValue(Stack *S)
{
    if(S->top>=0)
    {
        printf("the stack %dst value pop out: %d\n",S->top+1,S->Data[--S->top]);
    }
    else
    {
        printf("The Stack is empty\n");
    }
}

//推断栈空
void IsEmpty(Stack *S)
{
    if(S->top==-1)
    {
        printf("The Stack is empty.\n");
    }
    else
    {
        printf("The stack is not empty.\n");
    }
}


//清空栈
void ClearStack(Stack *S)
{
    S->top=-1;
}

//遍历栈
void ScanStack(Stack *S)
{
    int i;
    int len=S->top-1;
    int StackArray[len];
    for(i=len;i>0;i--)
    {
        StackArray[i]=S->Data[i--];
    }
    printf("The all stack member(from top to bottom) is:\n");
    while(len>=0)
    {
        printf("%d ",S->Data[len--]);
    }
    printf("\n");
}

void main()
{
    Stack S;

    InitStack(&S);
    PushStackValue(&S);
    ScanStack(&S);
    IsEmpty(&S);
    PopStackValue(&S);
    PopStackValue(&S);
    PopStackValue(&S);
    PopStackValue(&S);
}


执行结果例如以下:




转载请注明:刘

版权声明:本文博客原创文章。博客,未经同意,不得转载。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值