- 链式结构的基础:(结点和链)
typedef Stack_entry Node_entry;
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;
}
- 链栈的实现:
#include <iostream>
#include <cstdio>
using namespace std;
typedef char Stack_entry;
enum Error_code{
overflow, underflow, success
};
class Stack{
protected:
Node *top_node;
public:
Stack();
~Stack();
bool empty() const;
Error_code push(const Stack_entry & item);
Error_code pop();
Stack_entry top(Stack_entry & item) const;
void Stack::operator = (const Stack & original);
Stack(const Stack & original);
void print();
};
Stack::Stack(){
top_node = NULL;
}
Stack::~Stack(){
while (! empty())
pop();
}
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;
}
Stack_entry Stack::top(Stack_entry & item) const{
if(top_node == NULL) return 0;
item = top_node->entry;
return item;
}
bool Stack::empty() const{
if(top_node == NULL) return true;
else return false;
}
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_node = new_copy->next;
}
}
while (!empty())
pop();
top_node = new_top;
}
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_node = new_copy->next;
}
}
}
void Stack::print(){
Node <char>*new_node = top_node;
while(new_node != NULL){
cout << new_node->entry << " ";
new_node = new_node->next;
}
}