/* Stack.h - by Chimomo */ #ifndef Stack_H #define Stack_H typedef int Item; typedef struct node * PNode; /*栈结点*/ typedef struct node { Item data; PNode next; } Node; /*栈*/ typedef struct stack { PNode top; int size; } Stack; /*创建空栈*/ Stack *InitStack(); /*判断栈是否为空*/ int IsEmpty(Stack *ps); /*元素入栈*/ PNode Push(Stack *ps, Item item); /*元素出栈*/ PNode Pop(Stack *ps, Item *pitem); /*返回栈顶元素*/ PNode GetTop(Stack *ps, Item *pitem); /*返回栈的大小*/ int GetSize(Stack *ps); /*遍历栈并访问visit函数*/ void StackTraverse(Stack *ps, void (*visit)(Item item)); /*清空栈*/ void ClearStack(Stack *ps); /*销毁栈*/ void DestroyStack(Stack *ps); #endif
/* Stack.c - by Chimomo */ #include<malloc.h> #include<stdlib.h> #include"Stack.h" /*创建空栈*/ 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; } } /*元素入栈*/ PNode Push(Stack *ps, Item item) { PNode pnode = (PNode)malloc(sizeof(Node)); if(pnode != NULL) { pnode->data = item; pnode->next = GetTop(ps,NULL); ps->size++; ps->top = pnode; } return pnode; } /*元素出栈*/ 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->next; free(p); } return ps->top; } /*返回栈顶元素*/ PNode GetTop(Stack *ps, Item *pitem) { if(IsEmpty(ps) != 1 && pitem != NULL) { *pitem = ps->top->data; } return ps->top; } /*返回栈的大小*/ int GetSize(Stack *ps) { return ps->size; } /*遍历栈并访问visit函数*/ void StackTraverse(Stack *ps,void (*visit)(Item item)) { PNode p = ps->top; int i = ps->size; while(i--) { visit(p->data); p = p->next; } } /*清空栈*/ void ClearStack(Stack *ps) { while(IsEmpty(ps) != 1) { Pop(ps,NULL); } } /*销毁栈*/ void DestroyStack(Stack *ps) { if(IsEmpty(ps) != 1) { ClearStack(ps); } free(ps); }
时间: 2024-10-02 19:31:04