栈基本操作(C++实现)
2012-12-23 20:22
393 查看
#include <iostream> using namespace std; class ListStack; //提前声明,友元函数需要 class ListNode { friend class ListStack; public: ListNode(int value):data(value), next(0) {} private: int data; ListNode *next; }; class ListStack { public: ListStack():top(0) {} //构造函数 ListStack(const ListStack&); //拷贝构造函数 ~ListStack(); //析构函数 ListStack& operator=(const ListStack&); //赋值函数 bool isempty()const; //判空 void push(int); //入栈 bool pop(); //出栈 bool get_top(int&)const; //取栈顶元素 protected: private: ListNode *top; void copy(const ListStack&); //拷贝功能函数 void clear(); //清空函数,实现析构 }; //拷贝功能函数 void ListStack::copy(const ListStack& other) { top = 0; ListNode *tmp = other.top; ListNode *prenode; while (tmp) { ListNode *newnode = new ListNode(tmp->data); if (top == 0) { top = newnode; } else { prenode->next = newnode; } prenode = newnode; tmp = tmp->next; } } //清空栈函数 void ListStack::clear() { while (top) { ListNode *delnode = top; top = top->next; delete delnode; } } //拷贝构造函数 ListStack::ListStack(const ListStack& other) { copy(other); } //析构函数 ListStack::~ListStack() { clear(); } //赋值函数 ListStack& ListStack::operator=(const ListStack& other) { if (this != &other) { clear(); copy(other); } return *this; } //判栈空函数 bool ListStack::isempty()const { return top == 0; } //入栈函数 void ListStack::push(int value) { ListNode *newnode = new ListNode(value); newnode->next = top; top = newnode; } //出栈函数 bool ListStack::pop() { if (isempty()) { return false; } ListNode *delnode = top; top = top->next; delete delnode; return true; } //取栈顶元素 bool ListStack::get_top(int &value)const { if (isempty()) { return false; } value = top->data; return true; } //主函数 int main() { ListStack s1; for (int i=1; i<=6; ++i) { s1.push(i); } ListStack s2(s1); ListStack s3; s3 = s1; int value; while (s1.get_top(value)) { s1.pop(); cout << value << " "; } cout << endl << "s1 已经清空" << endl; while (s2.get_top(value)) { s2.pop(); cout << value << " "; } cout << endl << "s2已经清空" << endl; while (s3.get_top(value)) { s3.pop(); cout << value << " "; } cout << endl << "s3已经清空" << endl; return 0; }
相关文章推荐
- C++实现二叉搜索树基本操作(递归+非递归+应用)
- 【c++】模拟实现栈 类模板(Stack的基本操作)
- 顺序表的基本操作——C++实现
- 详细的单链表基本操作C/C++实现
- C++实现有向权图的基本操作,界面友好,操作方便,运行流畅
- C++实现有向权图的基本操作,界面友好,操作方便,运行流畅
- 【数据结构】双向循环线性表的基本操作--C++/C实现
- C++实现普通队列,循环队列的基本操作(初始化,入队,出队,获取队列首元素等)
- C++实现顺序表的基本操作
- C++实现shapefile文件的读写和基本功能的操作
- c/c++ 数据结构-线性表(单链表基本操作的实现)
- 顺序栈的基本操作实现c++
- 链式栈的基本操作实现c++
- 【代码】C++实现二叉树基本操作及测试用例
- 二叉树的基本操作 C++代码实现
- C++实现链表基本操作
- 顺序队列的基本操作实现c++
- 【数据结构】双向循环线性表的基本操作--C++/C实现
- C++实现栈的基本操作
- 二叉树的基本操作以及相关问题的求解—C++实现