算法:栈的实现

stack.h

#ifndef _STACK_H
#define _STACK_H

struct Node;
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty(Stack S);
Stack CreateStack(void);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
ElementType Pop(Stack S);
#endif

struct Node
{
    ElementType element;
    PtrToNode Next;
};

stack.c

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

int IsEmpty(Stack S)
{
    return S->Next==NULL;
}
Stack CreateStack(void)
{
    Stack S;
    S=malloc(sizeof(struct Node));
    if(S==NULL){
        printf("out of space");
        exit(1);
    }
    MakeEmpty(S);
    S->Next=NULL;
    return S;
}
void MakeEmpty(Stack S)
{
    if(S==NULL){
        printf("Must CreateStack first");
    }
    while(!IsEmpty(S)){
        Pop(S);
    }
}
void Push(ElementType X,Stack S)
{
    PtrToNode P;
    P=malloc(sizeof(struct Node));
    if(P==NULL){
        printf("out of space");
        exit(1);
    }
    P->element=X;
    P->Next=S->Next;
    S->Next=P;
}
ElementType Pop(Stack S)
{
    PtrToNode P;
    ElementType X;
    if(S==NULL){
        return 0;
    }
    P=S->Next;
    if(P!=NULL){
        X=P->element;
        S->Next=P->Next;
        free(P);
        return X;
    }
    return 0;
}

 

posted @ 2017-03-07 20:54  jmst  阅读(244)  评论(0编辑  收藏  举报