通过带有头节点的单链表来实现栈。
我们通过在链表的表头插入来实现push,删除表顶端元素实现pop,top操作只是返回表顶端元素,空栈时只有一个头节点。
stack.h
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef int ElementType;
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
Stack CreateSatck(void);
int IsEmpty(Stack S);
void DisposeStack(Stack S); //销毁栈
void MakeEmpty(Stack S); //创建一个空栈
void Push(Stack S,ElementType X); //X入栈
ElementType Top(Stack S);
void Pop(Stack S); //出栈
#endif // STACK_H_INCLUDED
stack.c
#include"..\fatal.h"
#include"stack.h"
#include<stdio.h>
#include<stdlib.h>
struct Node{
ElementType Element;
PtrToNode Next;
};
int IsEmpty(Stack S){
return S->Next == NULL;
}
Stack CreateStack(void){
Stack S = malloc(sizeof(struct Node));
if(S == NULL)
FatalError("Out of Space!!");
S->Next = NULL;
return S;
}
void DisposeStack(Stack S){
MakeEmpty(S);
free(S);
}
void MakeEmpty(Stack S){
if(S == NULL)
Error("Must use CreatStack first");
else
while(!IsEmpty(S))
Pop(S);
}
void Push(Stack S, ElementType X){
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
FatalError("Out of space!!");
else{
TmpCell->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;`
}
}
ElementType Top(Stack S){
if(IsEmpty(S))
Error("Empty stack");
return S->Next->Element;
}
void Pop(Stack S){
PtrToNode FirstCell;
if(IsEmpty(S))
Error("Empty Stack");
else{
FirstCell = S->Next;
S->Next = FirstCell->Next;
free(FirstCell);
}
}
int main(){
Stack S = CreateStack();
//测试Push()
Push(S,1);
Push(S,2);
//测试Top()
printf("%d\n",Top(S));
//测试Pop()
Pop(S);
printf("%d\n",Top(S));
DisposeStack(S);
return 0;
}