有没有大神,帮忙瞅一下呀
[local]1[/local]
程序代码:
#include "stdio.h" #include "malloc.h" #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 Node { SElemType data; //结点的数据 struct Node *next; //下一个结点的地址 } Node, *LinkNode; typedef struct { LinkNode top; //指向栈顶 }LinkStack; //初始化:分配内存,初始容量LIST_INIT_SIZE,栈顶栈底的初始值相同 Status InitStack(LinkStack &s) { s.top = (LinkNode)malloc(sizeof(Node));//产生头节点 if (s.top == NULL) return ERROR; s.top->next = NULL; return OK; } //销毁栈:释放栈的内存 Status DestroyStack(LinkStack &s) { LinkNode p, q; if (s.top == NULL) return ERROR; p = s.top->next; while (p != NULL) { q = p->next; free(p); p = q; } s.top = NULL; return OK; } //清空栈:使栈顶移至栈底位置 Status ClearStack(LinkStack &s) { return OK; } //判空 Status StackEmpty(LinkStack s) { if (s.top == NULL) return ERROR; if (s.top->next == NULL) return TRUE; else return FALSE; } int StackLength(LinkStack s) { int i = 0; if (s.top == NULL) return ERROR; LinkNode p; p = s.top->next; while (p != NULL) { i++; p = p->next; } return i; } //取栈顶元素值,存入e中,栈顶不变 Status GetTop(LinkStack s, SElemType &e) { if (s.top == NULL) return ERROR; e = s.top->next->data; return OK; } //入栈操作,若栈已满,则重新分配,并stacksize增大,栈顶改变 Status Push(LinkStack &s, SElemType e) { LinkNode p; p = (LinkNode)malloc(sizeof(Node)); p->data = e; p->next = s.top->next; s.top->next = p; return OK; } Status Pop(LinkStack &s, SElemType &e) { if (s.top == NULL) return ERROR; e = s.top->next->data; LinkNode p; p = s.top->next; s.top->next = p->next; free(p); return OK; } Status StackTraverse(LinkStack s) { if (s.top == NULL) { printf("栈未分配内存!n"); return ERROR; } if (s.top->next == NULL) { printf("栈中无数据!n"); return OK; } printf("栈中的数据有:"); LinkNode p; p = s.top->next; while (p != NULL) { printf(" %d ", p->data); p = p->next; } printf("n"); return OK; } void main() { LinkStack s; InitStack(s); Push(s, 1); Push(s, 2); Push(s, 3); Push(s, 4); Push(s, 5); SElemType e; GetTop(s, e); printf("栈顶元素:%dn", e); Push(s, 115); int l = StackLength(s); printf("栈长度为:%dn", l); StackTraverse(s); Pop(s, e); StackTraverse(s); Pop(s, e); StackTraverse(s); DestroyStack(s); }