栈stack的C实现

头文件——————————————————————————
#ifndef _STACK_H_
#define _STACK_H_
#include <stdlib.h>
#define Element int
struct node
{
     Element data;
     struct node *next;
};
typedef struct node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty(Stack s);
Stack CreateStack();
void DestroyStack(Stack s);
void MakeEmpty(Stack s);
void Push(Element x, Stack s);
Element Top(Stack s);
void Pop(Stack s);
#endif
源文件————————————————————————————
#include "./Stack.h"

int IsEmpty(Stack s)
{
     return s->next == NULL;
}
Stack CreateStack()
{
     Stack s = (Stack)malloc(sizeof(struct node));
     if(NULL == s) return NULL;
     s->next = NULL;
     return s;
}
void DestroyStack(Stack s)
{
     MakeEmpty(s);
     free(s);
}
void MakeEmpty(Stack s)
{
     while(!IsEmpty(s))
          Pop(s);
}
void Push(Element x, Stack s)
{
     if(NULL == s) return ;
     PtrToNode p = (PtrToNode)malloc(sizeof(struct node));
     if(NULL == p) return ;
     p->data = x;
     p->next = s->next;
     s->next = p;
}
Element Top(Stack s)
{
     return s->next->data;
}
void Pop(Stack s)
{
     PtrToNode p = s->next;
     s->next = p->next;
     free(p);
}

  

posted @ 2013-07-20 18:40  老司机  阅读(285)  评论(0编辑  收藏  举报