和单链表差不多,就不多说了。
特别注意在插入和删除链表元素操作时,仔细考虑该元素与相邻元素的前向指针、和后续指针的改变。
struct Node { int val; Node* pret; Node* next;};Node* cre_list(int n) //创建双向链表 n代表元素个数{ Node* head_temp = NULL; if (n > 0) { Node* head = new Node; head->val = rand()%100; head->pret = NULL; head->next = NULL; head_temp = head; for (int i = 1 ; i < n;++i) { Node* temp = new Node; temp->val = rand()%100; temp->next = NULL; temp->pret = head; head->next = temp; head = temp; } } return head_temp;}int get_len(Node* head) //获得双向链表长度{ int num = 0 ; Node* temp = head; while (temp != NULL) { ++num; temp = temp->next; } return num;}void display(Node* head) //输出元素{ Node* temp = head; while (temp != NULL) { cout<val<<' '; temp = temp->next; } cout< len) { return; } Node* temp = head; Node* new_one = new Node; new_one->val = n; if (pos == 0) //插入在第一个位置 3 { new_one->pret = NULL; new_one->next = temp; temp->pret = new_one; head = new_one; } else if (pos == len) //插入到最后一个位置 3 { new_one->next = NULL; for (int i = 1; i < pos;++i) { temp = temp->next; } temp->next = new_one; new_one->pret = temp; } else //插入到中间 4 { for (int i = 1 ; i < pos;++i) { temp = temp->next; } Node* temp2 = temp->next; new_one->next = temp2; temp2->pret = new_one; new_one->pret = temp; temp->next = new_one; }}void del_node(Node* &head,int n) //删除节点{ Node* temp = head; if (head->val == n) //删除的是头节点 2 { temp = head->next; temp->pret = NULL; delete head; head = temp; } else // { temp = temp->next; while (temp != NULL) { if (temp->val == n) { if (temp->next == NULL) //删除的是最后个节点 1 { Node* temp2 = temp->pret; temp2->next = NULL; delete temp; } else //删除中间部分的节点 2 { Node* temp2 = temp->next; Node* temp1 = temp->pret; temp1->next = temp2; temp2->pret = temp1; delete temp; } return; } temp = temp->next; } } return;}