#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int SElemType; typedef struct StackNode{ SElemType data; struct StackNode *next; }StackNode,*LinkStack; // 构造空栈 Status InitStack(LinkStack &S) { S = NULL; return OK; } // 销毁栈 Status DestroyStack(LinkStack &S) { S = NULL; free(S); return OK; } // 清空栈 Status ClearStack(LinkStack &S) { S = NULL; return OK; } // 判断栈是否为空 Status StackEmpty(LinkStack S) { if(!S) return TRUE; return ERROR; } // 获取栈的长度 int StackLength(LinkStack S) { return 0; } // 获取栈顶元素 Status GetTop(LinkStack S,SElemType &e) { if(S != NULL) e = S->data; return OK; } // 插入元素 Status Push(LinkStack &S,SElemType e) { LinkStack p = (LinkStack)malloc(sizeof(StackNode)); p->data = e; p->next = S; S = p; return OK; } // 删除栈顶元素,并用e返回其值w Status Pop(LinkStack &S,SElemType &e) { if(S == NULL) return ERROR; e = S->data; LinkStack p = (LinkStack)malloc(sizeof(StackNode)); p = S; S = S->next; free(p); return OK; }
测试
int main() { LinkStack S; InitStack(S); Push(S,1); Push(S,2); int e; GetTop(S,e); printf("%d\n",e); Pop(S,e); printf("%d\n",e); GetTop(S,e); printf("%d\n",e); return 0; }