跳到正文

个人记录

双向链表模板

isItTrue约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年1月4日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前
C++
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node{
    int L, R;//表示编号
}a[100003];
int n, m;
//语句顺序不可调换
inline void addRight(int x, int pos) { //插入右边
    a[x].L = pos;//插入的元素x的左端点指向pos
    a[a[pos].R].L = x;//pos的右端点指向元素pos'的左端点指向x
    a[x].R = a[pos].R;//x的右端点指向pos指向的右端点
    a[pos].R = x;//pos的右端点指向x
}
inline void addLeft(int x, int pos) { //插入左边
    a[x].R = pos;
    a[a[pos].L].R = x;
    a[x].L = a[pos].L;
    a[pos].L = x;
}
inline void del(int x) {
    if(a[x].L == -1) return;
    a[a[x].L].R = a[x].R;//把x的左端点指向的元素的右端点指向x的右端点
    a[a[x].R].L = a[x].L;//同理
    a[x].L = -1;
    a[x].R = -1;
}
inline void go() {
    int x = a[0].R;
    while(1) {
        cout<<x<<" ";
        if(a[x].R == -1) break;
        x = a[x].R;//更新x  by右节点
    }
}
inline void init() {//初始化
    for(int i = 1; i <= n; ++i) a[i].L = a[i].R = -1;
    a[1].R = -1; a[1].L = 0; a[0].R = 1;//头部元素预处理
}
int main() {
    scanf("%d", &n);
    int cmd1, cmd2;
    init();
    for(int i = 2; i <= n; ++i) {
        scanf("%d %d", &cmd1, &cmd2);
        if(!cmd2) addLeft(i, cmd1);
        else addRight(i, cmd1);
    }
    scanf("%d", &m);
    for(int i = 1; i <= m; ++i) {
        scanf("%d", &cmd1);
        del(cmd1);
    }
    go();
    return 0;
}
原文