栈基本操作(C++实现)

来源:互联网 发布:java path 编辑:程序博客网 时间:2024/06/10 20:31
#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;}

原创粉丝点击