我们可以用指针来实现一个链表,但每次均需要new一个结点,当数据非常大时,会超时。
在这里我们用数组模拟链表。
单链表
在单链表中,用的最多的便是邻接表(存储图和树)。
小编曾写过一篇博客,其中涉及到了邻接表,链接:
图,在此基础上做补充。
补充一道模板题。涉及到单链表的删除、插入等基本操作。
题目链接
题目描述:
1 <= M <= 100000,所有操作保证合法。
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int head; //表示头结点的下标。
int e[N], ne[N];
int idx = 0;
void init(){ //初始化
head = -1; //head指向-1,表示该链表为空链表。
idx = 0;
}
//将x插入到头结点
void add_to_head(int x){
ne[idx] = head;
e[idx] = x;
head = idx ++;
}
//将x这个点插入到下标是k的点后边。
void add(int k, int x){
ne[idx] = ne[k];
e[idx] = x;
ne[k] = idx ++;
}
//将下标是k的点后边的点删掉
void remove(int k){
ne[k] = ne[ne[k]];
}
int main(void){
int m;
cin >> m;
init();
while(m --){
char op;
int k, x;
cin >> op;
if(op == 'H'){
cin >> k;
add_to_head(k);
}
else if(op == 'D'){
cin >> k;
if(k == 0) head = ne[head];
else remove(k - 1);
}
else{
cin >> k >> x;
add(k - 1, x);
}
}
for(int i = head; i != -1; i = ne[i]) cout << e[i] << " ";
cout << endl;
}
双链表
优化某些问题。
- 对每个点,都有两个指针,一个指向前l[N],一个指向后r[N]。
- 下标为0的点,赋予head作用; 下标为1的点是最后的点。、
一道例题,展现删除、插入操作。
题目链接
题目描述:
输出格式:共一行,将整个链表从左到右输出。
数据范围 1<= M <= 100000, 所有操作保证合法。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int N = 1e5 + 10;
int e[N], l[N], r[N], idx;
//初始化
void init(){
//0表示左端点,1表示右端点
r[0] = 1, l[1] = 0;
idx = 2;
}
//在下标为k的右边插入
void add(int k, int x){
e[idx] = x;
r[idx] = r[k];
l[idx] = k;
l[r[k]] = idx;
r[k] = idx ++;
}
//在k的左边插入,直接调用add(l[k], x)即可。
//删除第k个点
void remove(int k){
r[l[k]] = r[k];
l[r[k]] = l[k];
}
int main(void){
int m;
ios::sync_with_stdio(false);
cin >> m;
init();
while(m --){
string s;
cin >> s;
int k, x;
if(s == "R"){
cin >> x;
//0和1只表示头和尾,在最右边插入只要在指向一的那个点的右边插入即可。
add(l[1], x);
}
else if(s == "L"){ //在最左边插入即在0的右边插入。
cin >> x;
add(0, x);
}
else if(s == "D"){
cin >> k;
remove(k + 1);
}
else if(s == "IL"){
cin >> k >> x;
add(l[k + 1], x);
}
else{
cin >> k >> x;
add(k + 1, x);
}
}
for(int i = r[0]; i != 1; i = r[i]) cout << e[i] << " ";
return 0;
}