数组是一种支持随机访问的数据结构,而链表支持在结构中间某个位置插入和删除数据的时间复杂度$O(1)$的数据结构。
struct Node{ int v; struct Node *p, *n; Node(int val): v(val) {} }; Node* head, * tail; void initialize(){ head = new Node(); tail = new Node(); head->n = tail; tail->p = head; } void insert(Node* p, int val){ Node* t = new Node(val); t->n = p->n; p->n->p = t; p->n = t; t->p = p; } void remove(Node* p){ p->n->p = p->p; p->p->n = p->n; delete p; } void free_node(){ Node* t; while(head){ t = head->n; delete head; head = t; } }
1. 邻接表
const int N = BUFSIZE; int idx = 1; int h[N], e[N], ne[N], w[N]; void add(int a, int b, int c){ e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; } void visit(int x){ for(int i = h[x]; i; i = ne[i]){ int j = e[i]; // todo: } }