链式栈
来源:互联网 发布:windows程序设计下载 编辑:程序博客网 时间:2024/05/17 06:55
链式栈不带有头结点,top指针直接指向栈顶。
LinkStack.h
#include<iostream>using namespace std;template<class T>struct LinkNode{ T data; LinkNode<T> *link; LinkNode(LinkNode<T>* pre = NULL){ link = pre; } LinkNode(T& x, LinkNode<T> *pre = NULL){ data = x; link = pre; }};template<class T>class LinkStack{protected: LinkNode<T> *top;public: LinkStack(){ top = NULL; } ~LinkStack(){ makeEmpty(); }; void makeEmpty(); bool isEmpty(){ return top == NULL ? true : false; } bool push(T &x); bool pop(T &x); bool getTop(T &x); int getSize(); void output();};template<class T>void LinkStack<T>::makeEmpty(){ LinkNode<T> *p = top; while (top != NULL){ p = top; top = top->link; delete p; }}template<class T>bool LinkStack<T>::push(T &x){ LinkNode<T> *p = new LinkNode<T>(x); if(p == NULL){ cout << "内存分配错误!" << endl; exit(1); } p->link = top; top = p; return true;}template<class T>bool LinkStack<T>::pop(T &x){ if (isEmpty() == true) return false; LinkNode<T> *del = top; x = del->data; top = top->link; delete del; return true;}template<class T>bool LinkStack<T>::getTop(T &x){ if (isEmpty() == true) return false; x = top->data; return true;}template<class T>int LinkStack<T>::getSize(){ if (isEmpty() == true) return 0; int cnt = 0; LinkNode<T> *p = top; while (p != NULL){ cnt++; p = p->link; } return cnt;}template<class T>void LinkStack<T>::output(){ cout << "top: "; LinkNode<T> *p = top; while (p != NULL){ cout << p->data << " "; p = p->link; } cout << endl;}
Test.cpp
#include"LinkStack.h"#include<string>using namespace std;void main(){ LinkStack<string> intStack; string str1 = "abcd", str2 = "efghji", str3 = "hello,world"; string str4, str5; intStack.push(str1); intStack.push(str2); intStack.push(str3); intStack.output(); cout << intStack.getSize() << endl; intStack.getTop(str4); cout << str4 << endl; intStack.pop(str5); intStack.output();}
0 0
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 栈链式
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 栈-链式
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- 链式栈
- Centos6.5 上Ansible 对Windows 管控
- 数据中心模块化和标准化(5-1)
- Oracle建立表空间和用户
- 用apache代理实现整合多个tomcat
- 自组织映射网络和学习向量量化网络
- 链式栈
- 聚集索引和非聚集索引(整理)
- 【小松教你手游开发】【unity实用技能】unity 地图选关功能设计
- Pow(x, n)
- Roads not only in Berland CodeForces 25D 并查集
- Symmetric Tree
- Timus OJ 1057 数位dp
- 离线安装 Android Studio 更新
- Web学习记录<二>PHP语法和MySQL小结