通用表

本文介绍了链表这一基本数据结构的实现方式,包括单向链表和双向链表的定义及操作方法,并提供了字符串处理和排列组合等应用场景的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链: 指针

实现:
验证算法对空的/只含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);
};
  1. 创建new_node指向待插入的结点
  2. 创建指向插入位置previous(前驱)和following(后继)的指针
  3. 使new_node等于previous->next,new_node->next等于following
  4. 特殊处理在List的起始位置插入
template<class List_entry>
class List{
public:   
   ~List();
   List(const List<List_entry>&copy);
   void operator=(const List<List_entry>&copy);
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个对象,将该对象插入到每个可能的位置生成新的排列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值