栈的数组实现

来源:互联网 发布:美国10月大非农数据 编辑:程序博客网 时间:2024/05/29 09:45

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


原创粉丝点击