单链表的升级--双向链表基操之插入操作和删除操作
作者:互联网
- 了解双向链表
- 看图思考什么是双向链表
- 理解
- 它可以有若干个数据域,可以存储更多的有用的数据!
- 它有两个指针域,一个指向它的前趋结点(pre),另一个指向它的后继结点(next);
- 它有优点:read、insert、delete更快了,空间换时间!
- 双向链表的插入操作
- 目标
把s结点插入到双向链表中 - 推演
- 代码
#include<iostream> using namespace std; struct Node { int data1, data2; Node *pre, *next; }; Node *head, *p, *q, *r; int x,y; int find(Node *head){ int n = 1; p = head; while (p != NULL) { n += 1; p = p->next; } return n; } void insertD(Node *head, int i, int m) { Node *s,*n;//定义两个Node指针 int j=0;//初值 s = new Node;//申请内存,s结点为新增插入的结点 s->data1 = m;//数据域赋值 n = head;// while((n->next != NULL) && (j<i)) { n = n->next; j++; } if(n->next == NULL) cout<< "没有位置了"; else { /* insert操作 */ n->pre->next = s; s->pre = n->pre; s->next = n; n->pre = s; } } int main(){ head = new Node;// p = new Node; q = new Node; r = new Node; head->next = p; p->data1 = 1; p->pre = head; p->next = q; q->data1 = 2; q->pre = p; q->next = r; r->data1 = 3; r->pre = q; r->next = NULL; cout << "这个双链表的结点数量为"<<find(head)<<"个"<<endl; insertD(head,2,77); cout << "这个双链表的结点数量为"<<find(head)<<"个"<<endl; return 0; }
- 双向链表的删除操作
-
目标
-
推演
-
代码
#include<iostream> using namespace std; struct Node { int data1, data2; Node *pre, *next; }; Node *head, *p, *q, *r; int x,y; int find(Node *head){ int n = 1; p = head; while (p != NULL) { n += 1; p = p->next; } return n; } void MydeleteD(Node *head, int i) { Node *n;// int j; n = head;// j = 0;//初值 while((n->next != NULL) && (j<i)) { n = n->next; j++; } if(n->next == NULL) cout<< "没有位置了"; else { /* delete操作 */ n->pre->next = n->next; n->next->pre = n->pre; } } int main(){ head = new Node;// p = new Node; q = new Node; r = new Node; head->next = p; p->data1 = 1; p->pre = head; p->next = q; q->data1 = 2; q->pre = p; q->next = r; r->data1 = 3; r->pre = q; r->next = NULL; cout << "这个双链表的结点数量为"<<find(head)<<"个"<<endl; MydeleteD(head,2); cout << "这个双链表的结点数量为"<<find(head)<<"个"<<endl; return 0; } ```
标签:pre,基操,head,--,Node,链表,int,new,next 来源: https://blog.csdn.net/qingdao_program/article/details/113830961