栈的定义:
栈是一种特殊的线性表
栈仅能在线性表的一端进行操作
栈顶:允许操作的一端
栈底:不允许操作的一端
栈的性质:
栈的操作:
创建栈
销毁栈
清空栈
进栈
出栈
获取栈的大小
获取栈顶元素
栈的顺序实现:
国嵌实现的栈是用以前实现的顺序表复用实现的,这里可以感受到代码复用的好处,顺序栈的实现,用很少的代码就能实现,而且用前使用的代码的来实现另一种数据结构,代码的鲁棒性也会更好。
附上实现代码:
定义的头文件:
#ifndef _SEQSTACK_H_
#define _SEQSTACK_H_
typedef void SeqStack;
SeqStack *SeqStack_Create(int capacity);
void SeqStack_Destroy(SeqStack *stack);
void SeqStack_Clear(SeqStack *stack);
int SeqStack_Push(SeqStack *stack,void *item);
void *SeqStack_Pop(SeqStack *stack);
void *SeqStack_Top(SeqStack *stack);
int Seqstack_Size(SeqStack *stack);
int SeqStack_Capacity(SeqStack *stack);
#endif
实现的c文件:
#include "SeqStack.h"
#include "SeqList.h"
//创建一个栈
SeqStack *SeqStack_Create(int capacity)
{
return SeqList_Create(capacity);
}
//销毁一个栈
void SeqStack_Destroy(SeqStack *stack)
{
SeqList_Destory(stack);
}
//清空一个栈
void SeqStack_Clear(SeqStack *stack)
{
SeqList_Clear(stack);
}
//压栈,相当于顺序表的尾部(或者头部插入)
int SeqStack_Push(SeqStack *stack,void *item)
{
return SeqList_Insert(stack,item,SeqList_Length(stack));//从尾部插入
}
//弹栈
void *SeqStack_Pop(SeqStack *stack)
{
SeqList_Delete(stack,SeqList_Length(stack)-1); //移除尾部第一个元素
}
//得到栈的容量
int SeqStack_Capacity(SeqStack *stack)
{
return SeqList_Capacity(stack);
}
//得到栈的大小
int SeqStack_Size(SeqStack *stack)
{
return SeqList_Length(stack);
}
//得到栈顶元素
void *SeqStack_Top(SeqStack *stack)
{
return SeqList_Get(stack,SeqList_Length(stack)-1);
}
测试代码:
#include <stdio.h>
#include "SeqStack.h"
int main(int argc, char *argv[])
{
SeqStack *stack = SeqStack_Create(20);
int a[10] = {0};
int i;
for(i=0; i<10; i++)
{
a[i] = i;
SeqStack_Push(stack,(void*)(a+i));
}
printf("Size = %d\n",*(int*)SeqStack_Top(stack));
printf("Capacity = %d\n",SeqStack_Capacity(stack));
while(SeqStack_Size(stack) > 0)
{
printf("Pop = %d\n",*(int*)SeqStack_Pop(stack));
}
SeqStack_Destroy(stack);
printf("Press enter to continue ...");
getchar();
return 0;
}