例题来自acwing826,不得不说y总代码确实简单易懂
实现一个单链表,链表初始为空,支持三种操作:
- 向链表头插入一个数;
- 删除第 k 个插入的数后面的数;
- 在第 k个插入的数后插入一个数。
现在要对该链表进行 M 次操作,进行完所有操作后,从头到尾输出整个链表。
注意:题目中第 k 个插入的数并不是指当前链表的第 k 个数。例如操作过程中一共插入了 n 个数,则按照插入的时间顺序,这 n 个数依次为:第 1 个插入的数,第 2 个插入的数,…第 n 个插入的数。
k是指插入的第几个数,这点要注意
#include<iostream>
#include<cstring>
using namespace std;
const int manx = 1e6;
//head头结点
//idx当前用到的点
//e[manx]当前节点的值
//ne[manx]当前节点指向的下一个位置,即节点的指针。
int head, idx, e[manx], ne[manx];
void yuuka()//初始化(如果你要问为什么叫yuuka,请搜索早濑优香)
{
head = -1, idx = 0;//-1空集
}
void add_h_yuuka(int x)//插入头结点
{
e[idx] = x;
ne[idx] = head;//与头结点互换指针,以前head指向的现在变为插入的ne[idx]接手
head = idx;
idx++;//向下一个节点移动
}
void addyuuka(int k, int x)//在节点k后插入
{
e[idx] = x;
ne[idx] = ne[k];
ne[k] = idx;//同理
idx++;
}
void yadayo(int k)
{
ne[k] = ne[ne[k]];//把指向k节点的指针指向k所指的节点,即略过了k,产生了删除操作。
}
int main()
{
int t;
cin >> t;
yuuka();
while (t--)
{
char s;
cin >> s; int cnt, ans;
if (s == 'H')
{
cin >> cnt;
add_h_yuuka(cnt);
}
else if (s == 'D')
{
cin >> cnt;
if (cnt == 0)
{
head = ne[head];
}
else
{
yadayo(cnt - 1);
}
}
else if (s == 'I')
{
cin >> cnt >> ans;
addyuuka(cnt - 1, ans);
}
}
for (int i = head; i != -1; i = ne[i]) cout << e[i] << ' ';
cout << endl;
}
其实为了防止我忘了才写的😋