双向链表与双向链表相比,每个元素都有两个指针分别指向前后两个元素,这意味着双向链表可以双向遍历。
简单例子如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <iostream> using namespace std; struct Node { int value; Node* prev; Node* next; }; class List { Node* head; public: void initList() { head = NULL; } bool insertNode(int value, int index) { Node* newnode = new Node(); newnode->value = value; if (index == 0) { newnode->prev = NULL; newnode->next = head; if(head) head->prev = newnode; head = newnode; return true; } int count = 0; Node* p = head; while (p) { if (p->next) { count++; if (count == index) { newnode->next = p->next; p->next->prev = newnode; p->next = newnode; newnode->prev = p; return true; } p = p->next; } return false; } return false; } bool deleteNode(int index) { Node* p = head; while (index>0) { index--; if (p->next) { p = p->next; } else return false; } if (p->prev) p->prev->next = p->next; else head = p->next; if (p->next) p->next->prev = p->prev; return true; } void display() { Node* p = head; while (p) { cout << p->value << " "; p = p->next; } cout << '\n'; } }; int main() { List* list = new List(); list->initList(); list->insertNode(5, 0); list->insertNode(6, 0); list->insertNode(7, 0); list->insertNode(9, 1); list->display(); list->deleteNode(2); list->display(); list->deleteNode(2); list->display(); return 0; }
|