#include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; using ElemType = int; // 双向链表结点 class Node { public: ElemType data; Node *next; Node *prior; }; // 初始化链表 void initList(Node *head, int n) { srand(time(NULL)); Node *p = head, *r = head; while (n--) { Node *q = (Node*)malloc(sizeof(Node)); q->data = rand()%100 - 1; p->next = q; q->prior = p; q->next = r; r->prior = q; p = q; } } // 增加某结点 void addNode(Node *head, int i, ElemType val) { int j = 0; Node *p = head; while (1) { if (j == i - 1) { Node *q = (Node*)malloc(sizeof(Node)); q->data = val; q->prior = p; q->next = p->next; p->next->prior = q; p->next = q; break; } j++; // p指向第j个结点 p = p->next; } } // 删除某结点 void delNode(Node *head, int i) { int j = 0; Node *p = head; while (1) { if (j == i) { p->prior->next = p->next; p->next->prior = p->prior; break; } j++; p = p->next; } } // 取某结点的值 void getNode(Node *head, int i) { int j = 0; Node *p = head; while (1) { if (j == i) { cout << "第" << i << "个结点的值为:" << p->data << endl; break; } j++; p = p->next; } } // 打印双向链表 void print(Node *head) { Node *p = head; p = p->next; while (p != head) { cout << p->data << " "; p = p->next; } cout << endl; } int main() { Node *head = (Node*)malloc(sizeof(Node)); head->prior = head; head->next = head; initList(head, 5); print(head); addNode(head, 2, 100); print(head); delNode(head, 2); print(head); getNode(head, 2); }