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

栈基本操作(C++实现)
#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;
}