欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈stack的C实现

程序员文章站 2024-01-14 16:31:16
...
头文件——————————————————————————
#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);
}