栈的链表实现

stack1.h

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

typedef  int  ElementType;

struct  node;
typedef  struct node *PtrToNode;
typedef  PtrToNode  Stack;

int  IsEmpty(Stack  S);
Stack  CreatStack(void);
void   MakeEmpty(Stack S);
Stack   Push(ElementType  X, Stack S);
Stack   Pop( Stack  S);
ElementType Top(Stack S);

#endif // STACK_H_INCLUDED

stack1.c

#include  
#include  
#include  "stack1.h"

struct  node
{
    ElementType  data;
    PtrToNode  next;
};


int  IsEmpty(Stack  S)
{
    return  S->next ==NULL;
}
Stack  CreatStack(void)
{
    Stack S=(Stack)malloc(sizeof(struct node));
    if(S==NULL)
        printf("out  of  space!!!");

    S->next=NULL;
    MakeEmpty(S);
    return  S;
}

void   MakeEmpty(Stack S)
{
    if(S==NULL)
        printf("error!!!");
    else
        while(!IsEmpty(S))
           S=Pop(S);
}


Stack   Push(ElementType  X, Stack S)
{
    Stack temp;
    temp=(Stack)malloc(sizeof(struct node));
    temp->data=X;
    temp->next=S->next;
    S->next=temp;

    return  S;
}


Stack   Pop(Stack  S)
{
    Stack temp;
    temp=S->next;
    S->next=S->next->next;
    free(temp);

    return S;
}


ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return  S->next->data;
    else
            return  0;
}





main.c

#include 
#include 
#include  "stack1.c"

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

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

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

    getchar();

    return 0;
}


你可能感兴趣的:(数据结构与算法)