C++类模板 实现栈的链式存储结构 《数据结构》(北京科海) (部分摘抄)
2012-11-16 11:03
661 查看
栈的链式存储称为链栈,链栈的基本操作的实现,本质上是单链表基本操作的简化,其算法都非常简单,其时间复杂度均为O(1),下面是实现代码:
如果有什么错误之处或好的建议,请大家提出来,互相学习,谢谢.....
/* Filename: LinkStack.h Description: The chained storage structure of stack Date: November 16, 2012 */ #ifndef LINKSTACK_H #define LINKSTACK_H #include <iostream> using namespace std; template<class T> class LinkStack; template<class T> class Node { friend class LinkStack<T>; public: Node():next(NULL) { } Node(const T &item):data(item), next(NULL) { } ~Node() { } private: T data; Node<T> *next; }; //栈的链式存储类定义 template<class T> class LinkStack { public: LinkStack() { top = NULL; } ~LinkStack() { Node<T> *p; while (top) { p = top->next; delete top; top = p; } } public: void Push(T x); T Pop(); T GetTop(); bool Empty(); void Print(); private: Node<T> *top; }; //栈的链式存储 类实现 template<class T> void LinkStack<T>::Push(T x) { Node<T> *newNode = new Node<T>(x); newNode->next = top; top = newNode; } template<class T> T LinkStack<T>::Pop() { if (top == NULL) { throw "溢出"; } T temp = top->data; Node<T> *tempNode = top; top = top->next; delete tempNode; return temp; } template<class T> T LinkStack<T>::GetTop() { if (top) { return top->data; } return NULL; } template<class T> bool LinkStack<T>::Empty() { if (top) { return false; } return true; } template<class T> void LinkStack<T>::Print() { if (!Empty()) { Node<T> *tempNode = top; while (tempNode) { cout << tempNode->data << " "; tempNode = tempNode->next; } cout << endl; } } #endif #include "LinkStack.h" int main() { LinkStack<int> Ls; Ls.Push(2); Ls.Push(4); Ls.Push(6); Ls.Print(); cout << "---------------------" << endl; cout << "栈顶元素:" << Ls.GetTop() << endl; Ls.Pop(); cout << "栈顶元素:" << Ls.GetTop() << endl; Ls.Print(); system("pause"); return 0; }
如果有什么错误之处或好的建议,请大家提出来,互相学习,谢谢.....
相关文章推荐
- C++类模板 实现队列的链式存储结构算法 《数据结构》(北京科海) 部分代码摘抄,自己编写运行
- C++类模板 实现顺序表 从《数据结构》(C++版) 北京科海摘抄
- C++类模板 实现双向循环链表的基本算法 《数据结构》(C++版 北京科海)中摘抄
- C++类模板 实现循环队列的顺序存储结构算法 《数据结构》(北京科海) 部分摘抄 自己编写实现
- C++类模板 实现两栈共享数组空间的算法 《数据结构》(北京科海) 自己摘抄完成
- 数据结构之动态数组 (C++类模板实现)
- C++类模板实现数据结构——栈
- 数据结构-红黑树(Red-Black Tree)的C++实现模板
- 你所不知道的事儿--C++类模板的声明和实现不能分离
- [数据结构]队列之顺序队列的类模板实现
- C++类模板实现顺序表
- 关于查询的部分数据结构实现-C语言
- 哈希(散列)表之开放定址法的C++类模板实现
- Spring定时任务的几种实现及部分模板
- (转)java实现基本数据结构(堆,栈,链表)——推荐后面的链表扩展部分
- 数据结构各种算法实现(C++模板)
- C++,数据结构,单向链表的实现及简单运用,运用模板
- C++类模板定义与实现的分离—学习C++数据抽象和问题求解
- [数据结构][二叉链表]二叉树链式存储结构的二叉链表实现
- C++类模板实现双链表