栈的实现
typedef struct node * PNode;
/*定义栈节点类型*/
typedef struct node
{
int data;//数据
PNode down;
}Node;
typedef struct stack
{
PNode top;
int size;
}Stack;
//创建一个栈
Stack *createStack()
{
Stack *ps = (Stack *)malloc(sizeof(Stack));
if(ps!=NULL)
{
ps->top = NULL;
ps->size = 0;
}
return ps;
}
//销毁栈
void DestoryStack(Stack *stack)
{
if (stack!=NULL) {
free(stack);
stack = NULL;
}
}
//是否是空栈
int IsEmptyStack(Stack *pStack)
{
if (pStack->top == NULL && pStack->size == 0) {
return 1;
}
return 0;
}
//获取栈尺寸
int GetStackSize(Stack *pStack)
{
if (pStack!=NULL) {
return pStack->size;
}
return 0;
}
//入栈
PNode PushStack(Stack *pStack,int data)
{
PNode pNode = (PNode)malloc(sizeof(Node));
if (pNode!=NULL) {
pNode->data = data;
pNode->down = pStack->top;
pStack->size++;
pStack->top = pNode;
}
return pNode;
}
//获取栈顶
PNode GetTopStack(Stack *stack,int *data)
{
if (IsEmptyStack(stack)!=1 && data !=NULL) {
*data =stack->top->data;
}
return stack->top;
}
//出栈
PNode pop(Stack *pStack,int *data)
{
PNode pNode = pStack->top;
if (IsEmptyStack(pStack)!=1 && pNode!=NULL) {
if(data!=NULL)
{
*data = pNode->data;
}
pStack->size --;
pStack->top = pStack->top->down;
free(pNode);pNode= NULL;
}
return pStack->top;
}
//遍历访问栈
void StackTraverse(Stack *ps,void (*visit)())
{
PNode pNode = ps->top;
while (pNode->down) {
visit(pNode->data);
pNode = pNode->down;
}
}
/*把栈置空*/
void ClearStack(Stack *ps)
{
while(IsEmptyStack(ps)!=1)
{
pop(ps,NULL);
}
}
/*销毁一个栈*/
void DestroyStack(Stack *ps)
{
if(IsEmptyStack(ps)!=1)
ClearStack(ps);
free(ps);
}
void print(int i)
{
printf("该节点元素为%d\n",i);
}
//调用如下
int main(int argc, const char * argv[]) {
@autoreleasepool {
int i,data;
Stack *ps = createStack();
printf("0-9依次入栈并输出如下:\n");
for(i=0;i<10;i++)
{
PushStack(ps,i);
GetTopStack(ps,&data);
printf("%d ",data);
}
printf("\n从栈顶到栈顶遍历并对每个元素执行print函数:\n");
StackTraverse(ps,print);
}
return 0;
}
LOG:
0-9依次入栈并输出如下:
0 1 2 3 4 5 6 7 8 9
从栈顶到栈顶遍历并对每个元素执行print函数: