http://blog.csdn.net/hopeyouknow/article/details/6725049
栈是常用的数据结构之一,下面给出一个链式栈的实现~~
头文件Stack.h
-
#ifndef Stack_H
-
#define Stack_H
-
-
typedef int Item;
-
typedef struct node * PNode;
-
-
typedef struct node
-
{
-
Item data;
-
PNode down;
-
}Node;
-
-
typedef struct stack
-
{
-
PNode top;
-
int size;
-
}Stack;
-
-
Stack *InitStack();
-
-
-
void DestroyStack(Stack *ps);
-
-
-
void ClearStack(Stack *ps);
-
-
-
int IsEmpty(Stack *ps);
-
-
-
int GetSize(Stack *ps);
-
-
-
PNode GetTop(Stack *ps,Item *pitem);
-
-
-
PNode Push(Stack *ps,Item item);
-
-
-
PNode Pop(Stack *ps,Item *pitem);
-
-
-
void StackTraverse(Stack *ps,void (*visit)());
-
-
#endif
实现部分Stack.c
-
#include"Stack.h"
-
#include
-
#include
-
-
Stack *InitStack()
-
{
-
Stack *ps = (Stack *)malloc(sizeof(Stack));
-
if(ps!=NULL)
-
{
-
ps->top = NULL;
-
ps->size = 0;
-
}
-
return ps;
-
}
-
-
-
int IsEmpty(Stack *ps)
-
{
-
if(ps->top == NULL && ps->size == 0)
-
return 1;
-
else
-
return 0;
-
}
-
-
-
int GetSize(Stack *ps)
-
{
-
return ps->size;
-
}
-
-
-
PNode Push(Stack *ps,Item item)
-
{
-
PNode pnode = (PNode)malloc(sizeof(Node));
-
if(pnode != NULL)
-
{
-
pnode->data = item;
-
pnode->down = GetTop(ps,NULL);
-
ps->size++;
-
ps->top = pnode;
-
-
}
-
return pnode;
-
}
-
-
-
PNode GetTop(Stack *ps,Item *pitem)
-
{
-
if(IsEmpty(ps)!=1&&pitem!=NULL)
-
{
-
*pitem = ps->top->data;
-
}
-
return ps->top;
-
}
-
-
-
-
PNode Pop(Stack *ps,Item *pitem)
-
{
-
PNode p = ps->top;
-
if(IsEmpty(ps)!=1&&p!=NULL)
-
{
-
if(pitem!=NULL)
-
*pitem = p->data;
-
ps->size--;
-
ps->top = ps->top->down;
-
free(p);
-
}
-
return ps->top;
-
}
-
-
-
void DestroyStack(Stack *ps)
-
{
-
if(IsEmpty(ps)!=1)
-
ClearStack(ps);
-
free(ps);
-
}
-
-
-
void ClearStack(Stack *ps)
-
{
-
while(IsEmpty(ps)!=1)
-
{
-
Pop(ps,NULL);
-
}
-
}
-
-
-
void StackTraverse(Stack *ps,void (*visit)())
-
{
-
PNode p = ps->top;
-
int i = ps->size;
-
while(i--)
-
{
-
visit(p->data);
-
p = p->down;
-
}
-
}
测试部分Test.c
-
#include"Stack.h"
-
#include
-
void print(Item i)
-
{
-
printf("该节点元素为%d\n",i);
-
}
-
main()
-
{
-
Stack *ps = InitStack();
-
int i,item;
-
-
printf("0-9依次入栈并输出如下:\n");
-
for(i=0;i<10;i++)
-
{
-
Push(ps,i);
-
GetTop(ps,&item);
-
printf("%d ",item);
-
}
-
-
printf("\n从栈顶到栈顶遍历并对每个元素执行print函数:\n");
-
StackTraverse(ps,print);
-
-
printf("栈中元素依次出栈并输出如下:\n");
-
for(i=0;i<10;i++)
-
{
-
Pop(ps,&item);
-
printf("%d ",item);
-
}
-
-
ClearStack(ps);
-
if(IsEmpty(ps))
-
printf("\n将栈置空成功\n");
-
DestroyStack(ps);
-
printf("栈已被销毁\n");
-
-
}
-
阅读(557) | 评论(0) | 转发(0) |