栈的ADT
栈是有限制的线性结构,即元素要遵照后进先出(LIFO)的原则进出栈。
栈的主要操作有进栈(Push),出栈(Pop),判空(IsEmpty)等。
栈可由顺序结构或者链式结构实现。
栈的链式结构实现
// stack.h声明栈的结构和部分操作
#ifndef DS_LINK_STACK_H
#define DS_LINK_STACK_H
// a link stack
typedef char DataType;
struct StackNode;
typedef struct StackNode StackNode;
typedef struct StackNode *Stack;
// return an empty stack
Stack CreateStack(void);
// return 1 if the stack is empty, otherwise return 0
int IsEmptyStack(const Stack stack);
// push the data on the top
void Push(Stack stack, DataType data);
// return the top data
DataType Pop(Stack stack);
// make an empty stack
void MakeEmptyStack(Stack stack);
// destory the stack
void DestoryStack(Stack stack);
#endif
// 栈的一些操作的实现
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
struct StackNode{
DataType data;
StackNode *next;
};
int IsEmptyStack(const Stack stack) {
return stack->next == NULL;
}
Stack CreateStack(void) {
Stack S = (Stack) malloc (sizeof(StackNode));
if(!S) {
printf("memory is full, create stack failed!\n");
return NULL;
}
S->next = NULL;
return S;
}
void Push(Stack stack, DataType data) {
if(stack == NULL) {
printf("must create a stack first!\n");
return ;
}
StackNode* node = (StackNode*) malloc (sizeof(StackNode));
node->data = data;
node->next = stack->next;
stack->next = node;
}
DataType Pop(Stack stack) {
if(stack == NULL) {
printf("must create stack first!\n");
exit(1);
}
if(IsEmptyStack(stack)) {
printf("stack is empty! no data to pop!\n");
exit(1);
}
StackNode *tmp = stack->next;
DataType data = tmp->data;
stack->next = tmp->next;
free(tmp);
return data;
}
void MakeEmptyStack(Stack stack) {
if(stack == NULL) {
printf("the stack doesn't exist! create one first!\n");
return ;
}
if(IsEmptyStack(stack)) {
printf("stack is already empty!\n");
return ;
}
while(!IsEmptyStack(stack)) {
Pop(stack);
}
}
void DestoryStack(Stack stack) {
if(stack == NULL) {
printf("the stack doesn't exist!\n");
return ;
}
free(stack);
}