#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;
}
結果: