栈的数组实现

stack2.h

#ifndef STACK2_H_INCLUDED
#define STACK2_H_INCLUDED

/**< 栈的数组实现 */
typedef  int  ElementType;
struct  stackrecord
{
    int  Capacity;
    int  TopOfStack;
    int  *Array;
};
typedef  struct  stackrecord  *Stack;

Stack  CreatStack(int  maxelement);   /**< 建一个空栈 */
int  IsEmpty(Stack  S);
int  IsFull(Stack  S);
void  DisposeStack(Stack  S);             /**< 销毁栈 */
void  MakeEmpty(Stack  S);
Stack Push(ElementType  X, Stack S);
Stack Pop(Stack S);
ElementType  Top(Stack  S);
ElementType  TopAndPop(Stack  S);            /**< 出栈及返回栈顶元素 */


#endif // STACK2_H_INCLUDED












stack2.c


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

   /**< 建一个空栈 */
Stack  CreatStack(int  maxelement)
{
    Stack  S=(Stack)malloc(sizeof(struct  stackrecord));
    if(S==NULL)
        printf("out  of  space!!!");

    S->Array=(ElementType *)malloc(sizeof(ElementType)*maxelement);
    if(S->Array ==NULL)
        printf("error:out  of  space!!!");

    MakeEmpty(S);
    return  S;
}

int  IsEmpty(Stack  S)
{
    return  S->TopOfStack == -1;
}

int  IsFull(Stack  S)
{
    return S->TopOfStack ==S->Capacity -1;
}

             /**< 销毁栈 */
void  DisposeStack(Stack  S)
{
    if(S!=NULL)
    {
        free(S->Array);
        free(S);
    }
}


void  MakeEmpty(Stack  S)
{
    S->TopOfStack =-1;
}


Stack Push(ElementType  X, Stack S)
{
    if(!IsFull(S))
        S->Array[++S->TopOfStack] =X;
    else
        printf("error:stack  is  full!");

    return  S;
}


Stack Pop(Stack S)
{
    if(!IsEmpty(S))
        S->TopOfStack--;
    else
        printf("error:stack is empty!!!");

     return  S;
}
ElementType  Top(Stack  S)
{
    if(!IsEmpty(S))
        return  S->Array[S->TopOfStack];
    else
    {
        printf("Error:satck  is empty!!");
        return  0;
    }
}

            /**< 出战及返回栈顶元素 */
ElementType  TopAndPop(Stack  S)
{
    if(!IsEmpty(S))
        return  S->Array[S->TopOfStack--];
    else
        printf("Error: stack  is empty!!");

    return 0;
}




main.c

#include <stdio.h>
#include <stdlib.h>
#include  "stack2.c"

int main()
{
    Stack  S=(Stack)malloc(sizeof(struct  stackrecord));
    int  c;

    S=CreatStack(10);

    while((c=getchar())!=EOF)
        S=Push(c,S);

    while(!IsEmpty(S))
    {
        printf("%d\t",Top(S));
        S=Pop(S);
    }


    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值