【普及】链表

· · 个人记录

链表

一种记录相邻元素(前驱,后继)地址的数据结构。

本讲义只介绍数组模拟链表,数组下标既可以当作地址,又可以当做编号。

种类

以双链表为例,讲解如何实现链表。

定义

struct Node{
  int nxt; // 后继元素地址
  int pre; // 前驱元素地址
  int x;   // 其他属性
};

// 空节点定义为地址为 0 的结点
Node a[N]; // 链表结点
int h, t; // 头、尾结点地址

空间复杂度 O(n)。

查

// 遍历链表中的每个结点
void Traverse(){
    for (int i = h; i; i = a[i].nxt){ 
  }
}

// 查找值为 x 的元素,返回元素地址
int Find(int x){
  for (int i = h; i; i = a[i].nxt){
    if (a[i].x == x){
      return i;
    }
  }
  return 0; // 不存在
}

// 查找从头结点开始的第 k 个元素,返回元素地址
int Find(int k){
  for (int i = h; i && k; i = a[i].nxt, k--){
  }
  return i;
}

时间复杂度均为 O(n)。

增 以在结点后方插入为例。

// 地址为 x 的结点插入到空链表
void Insert(int x){
  h = t = x;
}

// 地址为 x 的结点插入到链表头
void Insert(int x){
  a[x].nxt = h;
  a[h].pre = x;
  h = x;
}

// 地址为 x 的结点插入到链表尾
void Insert(int x){
  a[t].nxt = x;
  a[x].pre = t;
  t = x;
}

// 地址为 y 的结点插入到地址为 x 的结点之后
void Insert(int x, int y){
  a[y].nxt = a[x].nxt;
  a[a[x].nxt].pre = y;
  a[x].nxt = y;
  a[y].pre = x;
}

时间复杂度均为 O(1)。

删

// 删除链表中的最后一个结点
void Delete(int x){
  h = t = 0;
}

// 删除链表头结点
void Delete(){
  /*
  h1 = a[h].nxt;
  a[h].nxt = a[h1].pre = 0;
  h = h1;
  */
  h = a[h].nxt;
  a[a[h].pre].nxt = 0;
  a[h].pre = 0;
}

// 删除链表尾结点
void Delete(){
  /*
  t1 = a[t].pre;
  a[t].pre = a[t1].nxt = 0;
  t = t1;
  */
  t = a[t].pre;
  a[a[t].nxt].pre = 0;
  a[t].nxt = 0;
}

// 删除地址为 x 的结点
void Delete(int x){
  a[a[x].pre].nxt = a[x].nxt;
  a[a[x].nxt].pre = a[x].pre;
  a[x].nxt = a[x].pre = 0;
}

时间复杂度均为 O(1)。