链: 指针
实现:
验证算法对空的/只含1个的数据结构能正常工作
- 链式
- 避免使用多重引用(例如(p->next)->next,说明可以进行改进)
- 分配
- 顺序:算法对数据结构的要求简单且项所占的内存少
//由于struct的成员默认是公有的,所以用于实现未经封装的结构。
struct Node{
Node_entry entry;
//由于所有的指针在内存中所占的大小相同。为了避免循环定义,C++允许在定义类型前使用类型指针
Node *next;
Node();
Node(Node_entry item,Node *add_on=NULL);
};
Node::Node()
[
next=NULL;
]
Node(Node_entry item,Node* add_on)
{
entry=item;
next=add_on;
}
template<class Node_entry>
struct Node{
Node_entry entry;
Node<Node_entry> *next;
Node();
Node(Node_entry item,Node<Node_entry> *add_on=NULL);
};
- 创建new_node指向待插入的结点
- 创建指向插入位置previous(前驱)和following(后继)的指针
- 使new_node等于previous->next,new_node->next等于following
- 特殊处理在List的起始位置插入
template<class List_entry>
class List{
public:
~List();
List(const List<List_entry>©);
void operator=(const List<List_entry>©);
protected:
int count;
Node<List_entry> *head;
/*保存上次查找的位置,如果访问位于其后面的元素可以减少访问时间。*/
mutable int current_position;
mutable Node<List_entry>*current;
//通过下标找到对应的结点
Node<List_entry>*set_position(int position)const;
};
如果表需要频繁一定,考虑使用双向链表。
template<class Node_entry>
struct Node{
…
Node<Node_entry> *back;
Node(Node_entry item,Node<Node_entry> *link_next=NULL,Node<Node_entry> *link_back=NULL);
};
应用示例:字符串
数组链表(参考算法导论CP134)
typedef int index;
const int max_list=7;
template<class List_entry>
struct Node{
List_entry entry;
index next;
};
template<class List_entry>
class List{
public:
…
protected:
Node<List_entry>workspace[max_list];
index available;//下一个空闲位置的下标
index last_used;//最新元素的下标
index head;//最新元素的下标
int count;//已经存储的元素个数
index new_node();
void delete_node(index n);
int current_possion(index n)const;
index set_position(int position)const;
};
应用示例:
排列组合:生成n个对象的n!种排列
从1个对象开始,每增加1个对象,将该对象插入到每个可能的位置生成新的排列。