用数组模拟链表特别要注意一句:题目中第 k 个插入的数并不是指当前链表的第 k 个数。例如操作过程中一共插入了 n 个数,则按照插入的时间顺序,这 n 个数依次为:第 1 个插入的数,第 2 个插入的数,…第 n 个插入的数。
借用y总写的代码:
#include <iostream>
using namespace std;
const int N = 100010;
// head 表示头结点的下标
// e[i] 表示节点i的值
// ne[i] 表示节点i的next指针是多少
// idx 存储当前已经用到了哪个点
int head, e[N], ne[N], idx;// 初始化
void init()
{
head = -1;
idx = 0;
}// 将x插到头结点
void add_to_head(int x)
{
e[idx] = x, ne[idx] = head, head = idx ++ ;
}// 将x插到下标是k的点后面
void add(int k, int x)
{
e[idx] = x, ne[idx] = ne[k], ne[k] = idx ++ ;
}// 将下标是k的点后面的点删掉
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;
}作者:yxc
链接:https://www.acwing.com/activity/content/code/content/42977/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
链表的思想很简单,个人感觉对我的难点是对idx的理解,现在我想出来一些希望能给你带来帮助.
idx:时间顺序,其实这里的idx相当于开辟了一个节点,并记录这是第几次插入(这里的插入是对第几次的右边进行插入,前提要保证这次的插入要小于等于idx的值否则就会没有加入到链表上)列如:
输出结果为: