AcWing 827. 双链表
原题链接
简单
作者:
转码从入门到入坟
,
2021-03-27 14:07:12
,
所有人可见
,
阅读 276
C++ 代码
# include <iostream>
# include <string>
using namespace std;
const int N = 1e6 + 10;
const int DEFAULT = -100;
int l[N], r[N], head_idx, tail_idx, e[N], idx;
void init() {
head_idx = 0;
tail_idx = 1;
idx = 2;
r[head_idx] = tail_idx;
l[tail_idx] = head_idx;
r[tail_idx] = DEFAULT;
l[head_idx] = DEFAULT;
}
void addNodeTokRight(int k, int value) {
int k_idx = k + 1;
if (k == 0) {
k_idx = 0;
}
if (k_idx == 1) {
cout << "cannot add to tail's right\n";
exit(0);
}
e[idx] = value;
l[idx] = k_idx;
r[idx] = r[k_idx];
l[r[k_idx]] = idx;
r[k_idx] = idx;
idx++;
}
void addNodeTokLeft(int k, int value) {
int k_idx = k + 1;
int kLeft_idx = l[k_idx];
addNodeTokRight(kLeft_idx - 1, value);
}
//在链表的最左端插入数 -> 在 head的右端插入
void addNodeToLeft(int value) {
addNodeTokRight(head_idx, value);
}
//在链表的最右端插入数 -> 在tail的左节点的右端插入
void addNodeToRight(int value) {
int k_idx = l[tail_idx];
if (k_idx == 0) {
addNodeTokRight(0, value);
}
else {
addNodeTokRight(k_idx - 1, value);
}
}
//将第 k 个插入的数删除
void remove(int k) {
if (k < 1) {
cout << "k must be >= 1\n";
exit(0);
}
int k_idx = k + 1;
r[l[k_idx]] = r[k_idx];
l[r[k_idx]] = l[k_idx];
}
void printList() {
int index = head_idx;
index = r[index];
while (index != 1) {
printf("%d ", e[index]);
index = r[index];
}
printf("\n");
}
int main() {
int M;
cin >> M;
string op;
int k, x;
init();
for (int i = 0; i < M; i++) {
cin >> op;
if (op == "L") {
cin >> x;
addNodeToLeft(x);
}
else if (op == "R") {
cin >> x;
addNodeToRight(x);
}
else if (op == "D") {
cin >> k;
remove(k);
}
else if (op == "IL") {
cin >> k;
cin >> x;
addNodeTokLeft(k, x);
}
else if (op == "IR") {
cin >> k;
cin >> x;
addNodeTokRight(k, x);
}
else {
cout << "Illegal command\n";
return 0;
}
//printf("the %d op is : ", i);
//printList();
}
printList();
return 0;
}