链表 学习笔记

· · 个人记录

1.1 链表

链表,是一组位于任意位置的存储单元存储线性表的数据元素。这些存储单元可以连续,亦可以不连续。它的操作有初始化、添加、遍历、插入、删除、查找、释放等。链表分为单向链表和双向链表。

如图 1.1 所示:

\to\colorbox{grey}{\text{data}} \boxed{\text{next}}\to\colorbox{grey}{\text{data}} \boxed{\text{next}}\to\cdots\to\colorbox{grey}{\text{data}} \boxed{\text{next}}\to \small\text{(a)单向链表} \xleftrightarrow{}\boxed{\text{prev}}\colorbox{grey}{\text{data}} \boxed{\text{next}}\xleftrightarrow{}\boxed{\text{prev}}\colorbox{grey}{\text{data}} \boxed{\text{next}}\xleftrightarrow{}\cdots\xleftrightarrow{}\boxed{\text{prev}}\colorbox{grey}{\text{data}} \boxed{\text{next}}\xleftrightarrow{} \small\text{(b)双向链表} \text{图1.1 链表图示}

注意,单向和双向链表的 next 指针指向下一个节点,双向链表的 prev 指针指向上一个节点。而如果这是一个循环链表,则最后一个节点的 next 指针指向第一个节点,第一个节点的 prev 指针指向最后一个节点。

一般来讲,单向链表只有一个遍历方向,而双向链表有两个遍历方向,遍历速度更快。在需要频繁访问前后几个节点时可以使用双向链表。

链表主要可以用动态链表、静态链表或 STL list 来编写。

下面我们以一道题为例:

例1.1 P1996 约瑟夫问题

1.1.1 动态链表

动态链表适用于对内存要求很严格的题目,但是需要频繁管理空间,很容易出错。

以下代码是该题的动态链表做法:

#include<bits/stdc++.h>
using namespace std;
struct node{        //链表结点结构体 
    int data;       //编号 
    node *next;     //next指针 
};
int n,m;
int main(){
    cin>>n>>m;
    node *head,*p,*now,*prev;       //头指针,遍历指针,当前指针,prev指针
    head=new node;                  //new是分配新节点
    head->data=1;head->next=NULL;   //分配数据,->代表指针指向节点的参数 
    now=head;                       //当前指针是头指针
    for(int i=2;i<=n;i++){          //从第二个节点开始遍历 
        p=new node;                 //分配新节点 
        p->data=i;p->next=NULL;     //分配数据
        now->next=p;                //处理上一个节点的next指针
        now=p;                      //尾指针后移 
    } 
    now->next=head;                 //末节点的next指针指向头
    //-----------------建立链表------------------------------
    now=prev=head;                  //从第一个开始
    while((n--)>1){                 //人数大于1时
        for(int i=1;i<m;i++){       //数到 m 
            prev=now;               //记录上一个位置 
            now=now->next;          //当前节点指向下一个节点 
        } 
        printf("%d ",now->data);    //出局
        prev->next=now->next;       //修改上一个节点的next指针,跳过该节点
        delete now;                 //释放节点 
        now=prev->next;             //从下一个人开始报数 
    } 
    printf("%d",now->data);         //幸存者
    delete now;                     //释放节点 
    return 0;
}

1.1.2 静态链表

静态链表可以在对内存要求不那么严格的情况下使用,省去了动态分配与释放的麻烦。

以下给出三种静态链表做法:结构体单向链表、结构体双向链表、一维数组单向链表。

结构体单向链表:

#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
struct node{                        //静态单向链表结构体 
    int id,next;                
}nodes[maxn];                       //结构体静态数组 
int n,m;
int main(){
    cin>>n>>m;
    nodes[0].next=1;                //处理第0节点 
    for(int i=1;i<=n;i++){          //遍历 
        nodes[i].id=i;              //编号 
        nodes[i].next=i+1;          //下一个编号 
    }
    nodes[n].next=1;                //处理末节点编号
    int now=1,prev=1;               //当前节点编号与上一个节点编号 
    while((n--)>1){                 //人数大于1时
        for(int i=1;i<m;i++){       //数到 m 
            prev=now;               //记录上一个位置 
            now=nodes[now].next;    //当前节点变为下一个节点 
        } 
        printf("%d ",nodes[now].id);            //出局
        nodes[prev].next=nodes[now].next;       //处理上一个节点,使其跳过该节点 
        now=nodes[now].next;                    //新的当前节点 
    } 
    printf("%d",nodes[now].id);                 //幸存者
    return 0;
}

结构体双向链表:

#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
struct node{                        //静态单向链表结构体 
    int id,next,prev;               
}nodes[maxn];                       //结构体静态数组 
int n,m;
int main(){
    cin>>n>>m;
    nodes[0].next=1;                //处理第0节点 
    for(int i=1;i<=n;i++){          //遍历 
        nodes[i].id=i;              //编号 
        nodes[i].next=i+1;          //下一个编号
        nodes[i].prev=i-1;          //上一个编号 
    }
    nodes[n].next=1;                //处理末节点编号
    nodes[1].prev=n;                //处理头节点编号 
    int now=1;                      //当前节点编号与上一个节点编号 
    while((n--)>1){                 //人数大于1时
        for(int i=1;i<m;i++){       //数到 m 
            now=nodes[now].next;    //当前节点变为下一个节点 
        } 
        printf("%d ",nodes[now].id);                    //出局
        int prev=nodes[now].prev,next=nodes[now].next;  
        nodes[prev].next=nodes[now].next;               //处理上一个节点,使其跳过该节点
        nodes[next].prev=nodes[now].prev;               //处理下一个节点,使其跳过该节点 
        now=next;                                       //新的当前节点 
    } 
    printf("%d",nodes[now].id);                         //幸存者
    return 0;
}

一维数组单向链表:

#include<bits/stdc++.h>
using namespace std;
int nodes[105];             //一维数组链表,它的值为下一个编号 
int n,m;
int main(){
    cin>>n>>m;
    for(int i=1;i<n;i++)nodes[i]=i+1;   //遍历 
    nodes[n]=1;                         //尾节点下一个是头节点
    int now=1,prev=1;                   //当前节点和上一个节点 
    while((n--)>1){
        for(int i=1;i<m;i++){           //数到 m
            prev=now;                   //下一个节点的prev是当前节点
            now=nodes[now];             //下一个节点 
        } 
        cout<<now<<' ';                 //出局
        nodes[prev]=nodes[now];         //上一个节点的next为下一个节点,即跳过该节点
        now=nodes[prev];                //新的当前节点 
    } 
    cout<<now;                          //幸存者 
    return 0;
}

1.1.3 \mathbf{STL\ list}

我们的 C++ 库非常好用,在 STL (标准模板库)中有自带的 list 结构。以下是 list 的基础操作:

初始化:

函数名 含义 举例
list<type> listname 创建一个名为 listname 的链表,类型为 type list<int> a;
list<type> listname(n) 创建一个名为 listname 的链表,类型为 type,包含 n 个元素 list<int> b(5);
list<type> listname(n,x) 创建一个名为 listname 的链表,类型为 type,包含 n 个元素且全部赋初值 x list<int> c(3,100);
list<type> listname(list) 复制 list 内的元素至 listname 中 list<int> d(c);
list<type> listname(fir,end) 拷贝指定范围内的所有元素至 listname 中 int e[3]={0,1,2}; list<int> f(e,e+3);
list<type>::iterator name 定义一个名为 name,属于 type 类型的 list 迭代器 list<int>::iterator it;

函数:

函数名 含义 举例
iterator begin(),end() 列表的头指针和尾指针后一个指针 list<int>::iterator it=a.begin();
iterator rbegin(),rend() 列表的尾指针和头指针前一个指针 list<int>::reverse_iterator it=a.rbegin();
iterator cbegin(),cend(),crbegin(),crend() 上面的基础上增加 const 属性 list<int>::const_iterator it=a.cbegin(); list<int>::const_reverse_iterator itt=a.crbegin();
bool empty() 判断是否为空,是返回 1,不是返回 0 list<int> a(5,3); cout<<a.empty(); //0
int size() 返回列表包含的元素个数 cout<<a.size(); //5,按上一条来
int max_size() 返回列表最大能包含的元素个数 cout<<a.max_size(); //768614336404564650,按上一条来
reference front(),back() 返回列表头尾的引用 cout<<a.front(); //3,按上一条来
void assign(count,num)(fir,end) 将列表替换为 count 个 num,或将列表替换为指定范围内的值 a.assign(10,5); //替换为十个5,按上一条来
void emplace_front(x) 在列表头部插入一个值 a.emplace_front(3); //插入一个3,按上一条来
void push_front(x) 同上,但是慢 a.push_front(4); //插入一个4,按上一条来
void pop_front() 删除列表头部的值 a.pop_front(); //删除4,按上一条来
void emplace_back(x) 在列表尾部插入一个值 a.emplace_back(3); //插入一个3,按上一条来
void push_back(x) 同上,但是慢 a.push_back(4); //插入一个4,按上一条来
void pop_back() 删除列表尾部的值 a.pop_back(); //删除4,按上一条来
void emplace(iterator,x) 在指定位置插入一个值 a.emplace(a.begin(),1000); //在a的头部插入一个1000,按上一条来
void insert(iterator,x) 同上,但是慢 a.insert(a.begin(),500); //在a的头部插入一个500,按上一条来
void erase(iterator)(fir,end) 删除某位置或某区间的值 a.erase(a.begin(),a.end()); //清空a链表,按上一条来
void swap(a,b) 将两个相同类型的元素交换 无,太简单了
void resize(n,e) 重置链表的大小,大小小于 n 去尾部元素,大于 n 则用 e 添加 list<int> g(5,3); g.resize(8,8); //链表变为3,3,3,3,3,8,8,8
void clear() 清空链表 g.clear(); //清空g链表,按上一条来
void splice(iterator,list2)(iterator,list2,iterator)(iterator,list2,fir,end) 将 list2 的全部/单点/区间拼接至 list1 后 a.splice(a.begin(),b); //将b数组整体拼接至a数组的开头
void remove(num) 删除链表中所有等于 num 的元素 a.remove(10); //删除a链表中所有等于10的元素
void remove_if(func) 删除满足某个条件的所有元素 无
void unique() 链表去重 无
void merge(list) 合并两个 list,合并后依旧有序 无
void sort(fir,end,cmp) 给链表中的一个区间按 cmp 函数排序 无
void reverse(fir,end) 反转链表中的一个区间 无
void advance(iterator,num) 更改迭代器,使其指向第 num 个元素 无

绕得太远了,还是来看解题代码吧:

#include<bits/stdc++.h>
using namespace std;
list<int> nodes;                                //STL链表,它的值为编号 
int n,m;
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++)nodes.emplace_back(i); //遍历 
    list<int>::iterator it=nodes.begin();       //定义指针 
    while(nodes.size()>1){
        for(int i=1;i<m;i++){                   //数到 m
            it++;                               //下一个节点 
            if(it==nodes.end())it=nodes.begin();//到尾节点后再回头 
        } 
        cout<<*it<<' ';                         //出局
        list<int>::iterator next=++it;          //下一个节点指针 
        if(next==nodes.end())next=nodes.begin();//循环 
        nodes.erase(--it);                      //删除该节点 
        it=next;                                //新的当前节点 
    } 
    cout<<*it;                                  //幸存者 
    return 0;
}

那么链表的学习就告一段落了。以下是一些习题:

P1160 队列安排 及其 题解

Leetcode 链表题单 主题库21、92、206、237,剑指Offer 06、22、24、II 024、35、52。

\color{gold}\texttt{See you next time!}