一、栈的概念
栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
二、栈的实现
栈的基本操作包括增、删、改、查、判空、判满,此篇采用c++实现栈的基本操作。
“utility.h”内容如下:
//枚举
enum Error_code
{
success, fail, range_error, underflow, overflow, fatal,
not_present, duplicate_error, entry_inserted, entry_found,
internal_error
};
“stack.h”内容如下:
#include "utility.h"
#include <iostream>
using namespace std;
typedef double Stack_entry ;
typedef Stack_entry Node_entry;
struct Node {
// data members
Node_entry entry;
Node* next;
// constructors
Node();
Node(Node_entry item, Node* add_on = NULL);
};
class Stack {
public:
// Standard Stack methods
Stack();
bool empty() const;
Error_code push(const Stack_entry& item);
Error_code pop();
Error_code top(Stack_entry& item) const;
// Safety features for linked structures
~Stack();
Stack(const Stack& original);
void operator =(const Stack& original);
protected:
Node *top_node;
};
“stack.cpp”内容如下:
#include "stack.h"
#include <iostream>
using namespace std;
Stack::Stack()
{
top_node = NULL;
}
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;
return success;
}
Stack::~Stack()
{
while (!empty())
pop();
}
Stack::Stack(const Stack& original)
{
Node* new_copy, * original_node = original.top_node;
if (original_node == NULL)
top_node = NULL;
else
{
top_node = new_copy = new Node(original_node->entry);
while (original_node->next != NULL)
{
original_node = original_node->next;
new_copy->next = new Node(original_node->entry);
new_copy = new_copy->next;
}
}
}
void Stack::operator=(const Stack& original)
{
Node* new_top, * new_copy, * original_node = original.top_node;
if (original_node == NULL)
new_top = NULL;
else
{
new_copy = new_top = new Node(original_node->entry);
while (original_node->next != NULL)
{
original_node = original_node->next;
new_copy->next = new Node(original_node->entry);
new_copy = new_copy->next;
}
}
while (!empty())
pop();
top_node = new_top;
}