一、基本思路
1、单链表节点结构图
![在这里插入图片描述](https://img-blog.csdnimg.cn/71bbd49c87724994b53e96a4af81ca48.png#pic_center)
- 其中的 idx 表示的是当下要把第 k 个节点存在哪个索引的数组,要注意第k次插入和idx的关系
- 插入操作,第一步要先进行赋值
- 本链表为静态链表表示方式
2、将数值 x 插入到头结点
![在这里插入图片描述](https://img-blog.csdnimg.cn/da8889fe43aa4b66af45df2ed143ade7.png#pic_center)
3、将数值 x 插入到第 k 次插入的数后面
![在这里插入图片描述](https://img-blog.csdnimg.cn/b313d2f9900d46418a6ee7815eeb1c79.png#pic_center)
4、将第 k 次插入的数后面的数删除
![在这里插入图片描述](https://img-blog.csdnimg.cn/43d2cc989858488abd6538a29c849cbb.png#pic_center)
二、Java、C语言模板实现
![在这里插入图片描述](https://img-blog.csdnimg.cn/7a0eae4eb29f4736a46fd5161cebf40a.png#pic_center)
import java.util.*;
public class Main {
static int N = 100010;
static int[] e = new int[N];
static int[] ne = new int[N];
static int head, idx;
public static void init(){
head = -1;
idx = 1;
}
public static void addHead(int x){
e[idx] = x;
ne[idx] = head;
head = idx++;
}
public static void insertNode(int k, int x){
e[idx] = x;
ne[idx] = ne[k];
ne[k] = idx++;
}
public static void deleteNode(int k){
ne[k] = ne[ne[k]] ;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int M = scanner.nextInt();
int x,k;
init();
for (int i = 0; i < M; i++) {
String judge = scanner.next();
switch (judge){
case "H":
x = scanner.nextInt();
addHead(x);
break;
case "D":
k = scanner.nextInt();
if (k == 0){
head = ne[head];
}else {
deleteNode(k);
}
break;
case "I":
k = scanner.nextInt();
x = scanner.nextInt();
insertNode(k, x);
break;
default:
System.out.println("输入错误");
}
}
for (int i = head; i != -1; i = ne[i]) {
System.out.print(e[i] + " ");
}
}
}
```c
#include <iostream>
using namespace std;
const int N = 100010;
int head, e[N], ne[N], idx;
void init()
{
head = -1;
idx = 0;
}
void add_to_head(int x)
{
e[idx] = x, ne[idx] = head, head = idx ++ ;
}
void add(int k, int x)
{
e[idx] = x, ne[idx] = ne[k], ne[k] = idx ++ ;
}
void remove(int k)
{
ne[k] = ne[ne[k]];
}
int main()
{
int m;
cin >> m;
init();
while (m -- )
{
int k, x;
char op;
cin >> op;
if (op == 'H')
{
cin >> x;
add_to_head(x);
}
else if (op == 'D')
{
cin >> k;
if (!k) 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;
return 0;
}
三、注意事项
- 单链表其实可以在任意位置插入,但是若想时间复杂度为O(1),则只能在某一个点后面插入
- 原因:因为找不到上一个点的指针,只能从头遍历