栈的定义
栈是一种特殊的线性表
栈仅能在线性表的一端进行操作
栈顶(Top):允许操作的一端
栈底(Bottom):不允许操作的一端
栈的性质
栈的操作
栈的一些常用操作
创建栈
销毁栈
清空栈
进栈
出栈
获取栈顶元素
获取栈的大小
栈的顺序存储实现
顺序存储实现
下面的顺序栈是不能支持结构体的!
现在我们先来实现顺序栈,由于之前我们实现了顺序表,现在代码复用,用其来实现顺序栈。
eg:
SeqStack.h
#ifndef _SEQSTACK_H_ #define _SEQSTACK_H_ typedef void SeqStack; typedef void * Stack_element; SeqStack* SeqStack_Create(int capacity); void SeqStack_Destroy(SeqStack* stack); void SeqStack_Clear(SeqStack* stack); int SeqStack_Push(SeqStack* stack, Stack_element item); void* SeqStack_Pop(SeqStack* stack); void* SeqStack_Top(SeqStack* stack); int SeqStack_Size(SeqStack* stack); int SeqStack_Capacity(SeqStack* stack); #endif
SeqStack.c
1 #include "SeqStack.h" 2 #include "SeqList.h" 3 4 SeqStack* SeqStack_Create(int capacity) 5 { 6 return SeqList_Create(capacity); 7 } 8 9 void SeqStack_Destroy(SeqStack* stack) 10 { 11 SeqList_Destroy(stack); 12 } 13 14 void SeqStack_Clear(SeqStack* stack) 15 { 16 SeqList_Clear(stack); 17 } 18 19 int SeqStack_Push(SeqStack* stack, Stack_element item) 20 { 21 return SeqList_Insert(stack, item, SeqList_Length(stack));//压栈都是在尾部压入 22 } 23 24 void* SeqStack_Pop(SeqStack* stack) 25 { 26 return SeqList_Delete(stack, SeqList_Length(stack) - 1);//出栈是最后一个元素 27 } 28 29 void* SeqStack_Top(SeqStack* stack) 30 { 31 return SeqList_Get(stack, SeqList_Length(stack) - 1);//获取栈顶元素 32 } 33 34 int SeqStack_Size(SeqStack* stack) 35 { 36 return SeqList_Length(stack); 37 } 38 39 int SeqStack_Capacity(SeqStack* stack) 40 { 41 return SeqList_Capacity(stack); 42 }
SeqList.h (复用之前的代码)
1 #ifndef _SEQLIST_H_ 2 #define _SEQLIST_H_ 3 4 typedef void SeqList; 5 typedef void SeqListNode; 6 7 SeqList* SeqList_Create(int capacity); 8 9 void SeqList_Destroy(SeqList* list); 10 11 void SeqList_Clear(SeqList* list); 12 13 int SeqList_Length(SeqList* list); 14 15 int SeqList_Capacity(SeqList* list); 16 17 int SeqList_Insert(SeqList* list, SeqListNode* node, int pos); 18 19 SeqListNode* SeqList_Get(SeqList* list, int pos); 20 21 SeqListNode* SeqList_Delete(SeqList* list, int pos); 22 23 #endif