#endif //__LINKSTACK_H__
#include "LinkStack.h" #include <stdlib.h> LinkStack *Create_Stack() { LinkStack* s = (LinkStack*)malloc(sizeof(LinkStack)/sizeof(char)); if (s == NULL) { errno = MALLOC_ERROR; return NULL; } // 置空栈 s->top = NULL; return s; } int StackEmpty (LinkStack *s) { if (s == NULL) { errno = ERROR; return FALSE; } return s->top == NULL; } int Push (LinkStack *s, StackData x) { if (s == NULL) { errno = ERROR; return FALSE; } // 新建结点 Node* node = (Node*)malloc(sizeof(Node)/sizeof(char)); if (node == NULL) { errno = MALLOC_ERROR; return FALSE; } node->data = x; node->next = s->top; s->top = node; return TRUE; } int Pop (LinkStack *s, StackData *x) { if (s == NULL) { errno = ERROR; return FALSE; } if (StackEmpty(s)) { errno = EMPTY_STACK; return FALSE; } Node *p = s->top; *x = p->data; s->top = p->next; free(p); return TRUE; } int GetTop (LinkStack *s, StackData *x) { if (s == NULL) { errno = ERROR; return FALSE; } if (StackEmpty(s)) { errno = EMPTY_STACK; return FALSE; } *x = s->top->data; return TRUE; } // 销毁栈 int Destroy(LinkStack *s) { if (s == NULL) { errno = ERROR; return FALSE; } int x; while(StackEmpty(s) != TRUE) { Pop (s, &x); } free(s); return TRUE; }
#include <stdio.h> #include "LinkStack.h" int main() { LinkStack *s = Create_Stack(); if (s == NULL) { myError ("Create_Stack"); return -1; } if (StackEmpty(s)) { printf ("空栈\n"); } int x; if (Pop(s, &x) != TRUE) { myError ("Pop 错误"); } int i; for (i = 0; i < 10; i++) { Push(s, i); } char str[100]; for (i = 0; i < 12; i++) { if (Pop (s, &x) != TRUE) { sprintf (str, "Pop第%d个元素", i); myError (str); } printf ("x : %d\n", x); } if (Destroy(s) == FALSE) { myError ("Destroy"); } return 0; }