关闭

栈的数组实现

440人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:67559次
    • 积分:1443
    • 等级:
    • 排名:千里之外
    • 原创:73篇
    • 转载:22篇
    • 译文:0篇
    • 评论:12条
    最新评论