#include<iostream>
enum Error_code { success, fail, range_error, underflow, overflow, fatal, not_present, duplicate_error, entry_inserted, entry_found, internal_error }; //"utility.h"
using namespace std;
struct Node { //结构体
Node_entry entry; //数据域
Node *next; //指针域
Node(); //构造函数
Node(Node_entry item, Node *add_on = NULL); //带参数的构造函数
};
Node::Node()
{
next = NULL;
}
Node::Node(Node_entry item, Node *add_on)
{
entry = item;
next = add_on;
}
class Stack {
public:
Stack(); //构造函数
bool empty() const; //判断是否为空
Error_code push(const Stack_entry &item); //插入一个元素
Error_code pop(); //删除一个元素
Error_code top(Stack_entry &item) const; //读取栈顶元素
~Stack(); //析构函数
Stack(const Stack &original); //拷贝构造函数
void operator = (const Stack &original); //运算符重载
protected:
Node *top_node;
};
Stack::Stack() //构造函数
{
top_node= NULL;
}
Stack::Stack(const Stack &original) // 拷贝构造函数
{
Node *new_copy, *original_node = original.top_node; //定义两个新的链表,new_copy用来复制原链表,original_node用来遍历原链表
if (original_node == NULL) top_node = NULL; //如果原链表里没有数据则直接制空
else
{
top_node = new_copy = new Node(original_node->entry); //创建头节点,并且将top指针指向它
while (original_node->next != NULL) //遍历原链表和新链表,将原链表中的数据逐一赋给新链表
{
original_node = original_node->next;
new_copy->next = new Node(original_node->entry);
new_copy = new_copy->next;
}
}
}
bool Stack::empty() const //判断链表是否为空
{
return top_node == NULL;
}
Error_code Stack::push(const Stack_entry &item) //插入一个元素
{
Node *new_top = new Node(item, top_node); //定义一个新节点
if (new_top == NULL) return overflow; //判断链表空间是否溢出
top_node = new_top; //头指针指向新节点
return success;
}
Error_code Stack::pop() //删除一个元素
{
Node *old_top = top_node; //定义一个新节点指向栈顶
if (top_node == NULL) return underflow; //判断栈中是否有元素
top_node = old_top->next; //头指针向后移一位
delete old_top; //删除节点中的数据
return success;
}
Error_code Stack::top(Stack_entry &item) const //读取栈顶元素
{
if (top_node == NULL) return underflow; //判断栈中是否有元素
item = top_node->entry; //将栈顶元素的值赋给item
return success;
}
Stack::~Stack() //析构函数
{
while (!empty())
pop();
}
void Stack::operator = (const Stack &original) //"="重载
{
Stack new_copy(original); //调用构造函数
top_node = new_copy.top_node;
}
简单应用:
typedef int Node_entry;
typedef int Stack_entry;
#include "chainstack.cpp"
int main()
{
Stack chain1;
bool isempty;
int item;
chain1.push(3);
chain1.top(item);
cout << item << endl;
chain1.push(4);
chain1.push(5);
chain1.top(item);
cout << item << endl;
isempty = chain1.empty();
cout << isempty << endl;
chain1.pop();
chain1.top(item);
cout << item << endl;
}
结果: