码迷,mamicode.com
首页 > 其他好文 > 详细

栈的C数组实现

时间:2014-07-29 12:55:57      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:   顺序栈   数据结构   先进后出   

栈是一种先进后出的数据结构.

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


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


运行结果如下:

bubuko.com,布布扣



转载请注明作者:小刘

栈的C数组实现,布布扣,bubuko.com

栈的C数组实现

标签:   顺序栈   数据结构   先进后出   

原文地址:http://blog.csdn.net/u013018721/article/details/38262805

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!