数据结构:链栈
栈的定义:
当单链表限定只能在头部进行插入和删除操作的时候,就是链栈。同时把栈顶放在单链表的头部,使单链表的头指针和栈顶指针top合二为一,所以对于链栈,就不再需要头结点了。这时对链栈的push也就相当于单链表的头插法。
同时对链栈来说,基本不存在栈满的情况,除非内存已经没有可以使用的空间了,对于空栈来说,链表原定义是头指针指向空,那么链栈的空其实就是top==NULL的时候。
链栈的代码实现:
#include <iostream> #include <stdlib.h> using namespace std; /************************************************** * * 链栈的结构 * **************************************************/ typedef int SElemType; typedef struct StackNode { SElemType data; struct StackNode *next; }StackNode, *StackNodePtr; typedef struct LinkStack { StackNodePtr top; int count; }LinkStack; /************************************************** * * 链栈的操作函数 * **************************************************/ bool InitStack(LinkStack *s) { cout << "Init Stack ..." << endl; s->top = NULL; s->count = 0; return true; } /*将栈清空*/ bool ClearStack(LinkStack *s) { cout << "Clear Stack ..." << endl; if(s->top == NULL) { return true; } StackNodePtr p = s->top; StackNodePtr q = NULL; while(p) { q = p->next; free(p); p = q; }//while s->top = NULL; s->count = 0; return true; } /*判断栈是否为空*/ bool IsEmptyStack(LinkStack s) { return s.count == 0; } /*返回栈的长度*/ int StackLength(LinkStack s) { cout << "Stack Length: "; return s.count; } /*返回栈顶元素*/ bool GetTop(LinkStack s, SElemType *e) { if(s.top == NULL) { return false; } *e = s.top->data; cout << "Get Top Item" << *e << endl; return true; } /*进栈*/ bool Push(LinkStack *s, SElemType e) { cout << "Push Item " << e << endl; StackNodePtr p = (StackNodePtr)malloc(sizeof(StackNode)); p->data = e; p->next = s->top; s->top = p; s->count++; return true; } /*出栈*/ bool Pop(LinkStack *s, SElemType *e) { /*栈为空*/ if(s->top == NULL) { return false; } StackNodePtr p = s->top; s->top = p->next; *e = p->data; free(p); s->count--; cout << "Pop Item " << *e << endl; return true; } /*输出栈元素*/ bool StackTraverse(LinkStack s) { cout << "Stack Traverse ..." << endl; StackNodePtr p = s.top; while(p != NULL) { cout << p->data << ' '; p = p->next; } cout << endl; return true; } void main(void) { LinkStack ls; InitStack(&ls); for(int i = 0; i < 5; i++) { Push(&ls, i); } StackTraverse(ls); int result; GetTop(ls, &result); Pop(&ls, &result); StackTraverse(ls); if(!IsEmptyStack(ls)) { cout << StackLength(ls) << endl; } ClearStack(&ls); StackTraverse(ls); system("pause"); }
执行结果: