链栈的实现:注意 指针的方向 跟 单链表是反着的,其中S为头指针,为空时头指针==NULL
//链栈的创建实现---是运算受限的单链表,只能在链表头部进行操作 typedef struct StackNode { int data; struct StackNode *next; }StackNode,*LinkStack; LinkStack S;
入栈操作:
//链栈的入栈 bool PushLinkStack(LinkStack &s, int e) { StackNode *p = new StackNode; p->data = e; p->next = s; p = s; return true; }
链栈的删除-出栈:
//链栈的出栈 bool PopLinkStack(LinkStack &s, int &e) { StackNode *p; if (s == NULL) return false; e = s->data; p = s; s = s->next; delete p; return true; }
最终版代码:
//链栈的创建实现---是运算受限的单链表,只能在链表头部进行操作 typedef struct StackNode { int data; struct StackNode *next; }StackNode,*LinkStack; LinkStack S; //链栈的初始化 void InitLinkStack(LinkStack &s) { //栈顶指针(头指针置为空) s = NULL; } //判断链栈是否为空 bool EmptyListStack(LinkStack s) { if (s == NULL) return true; } //链栈的入栈 bool PushLinkStack(LinkStack &s, int e) { StackNode *p = new StackNode; p->data = e; p->next = s; s = p;//将栈顶指针指向新结点 return true; } //链栈的出栈 bool PopLinkStack(LinkStack &s, int &e) { StackNode *p; if (s == NULL) return false; e = s->data; p = s; s = s->next; delete p; return true; } //取栈顶元素 int GetLinkStackTop(LinkStack s) { if (s != NULL) return s->data; }