//双链表
#include<iostream>
using namespace std;
typedef struct DNode{
int data;
struct DNode *prev;
struct DNode *next;
}DNode,*DLinkList;
//初始化链表
void InitDLinkList(DLinkList &D){
D = new DNode;
D->prev = nullptr;
D->prev = nullptr;
}
//遍历链表
void Print_D(DLinkList &D){
DLinkList p = D->next;
if(D == NULL || D->next == NULL){
cout<<"双链表为空"<<endl;
return;
}
while(p != nullptr){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
//在D中第i个元素之前插入数据元素e
int Insert_D(DLinkList &D,int i,int e){
DLinkList p = D;
int j = 0;
while(p != nullptr && j<i-1){
p = p->next;//找到第i-1个元素
j++;
}
if(p == nullptr || j>i-1){
return -1;
}
DLinkList s = new DNode;
s->data = e;
//先更新新结点的前去和后继指针
s->next = p->next;
s->prev = p;
//再更新原链表中相邻结点的前驱和后继指针
if(p->next != nullptr){
p->next->prev = s;
}
p->next = s;
return 1;
}
int main() {
DLinkList L;
InitDLinkList(L);
Insert_D(L, 1, 1);
Insert_D(L, 2, 2);
Insert_D(L, 3, 3);
Insert_D(L, 4, 4);
Insert_D(L, 5, 5);
cout << "双链表: ";
Print_D(L);
Insert_D(L, 3, 10); // 在第3个元素之前插入10
cout << "插入10后的双链表: ";
Print_D(L);
return 0;
}