与单链表相比,增加了指向前驱的指针,便于找到当前结点的前驱。
图源百度
初始化
typedef int datatype;
struct nodes{
datatype data;
struct nodes *last,*next;
};
struct List{
struct nodes *head;
};
//创建头节点
void init(struct List *List){
nodes *head=(nodes*)malloc(sizeof(nodes));
head->next=NULL;
head->last=NULL;
List->head=head;
}
建立
头插法
连接1
连接2,3消失
连接4
连接5,6消失
//头插法
void createList(struct List *List){
datatype num;
cout<<"输入数据元素,当数据元素为-1时结束"<<endl;
while(cin>>num&&num!=-1){
nodes *temp=(nodes*)malloc(sizeof(nodes));
temp->data=num;
temp->next=(List->head)->next;
(List->head)->next=temp;
temp->last=List->head;
if(temp->next!=NULL){
(temp->next)->last=temp;
}
}
}
尾插法
连接1
连接2
连接3,4消失
更新tail
//尾插法
void createList(struct List *List){
nodes *tail=List->head;
datatype num;
cout<<"输入数据元素,当数据元素为-1时结束输入"<<endl;
while(cin>>num&&num!=-1){
nodes *temp=(nodes*)malloc(sizeof(nodes));
temp->data=num;
temp->next=NULL;
temp->last=tail;
tail->next=temp;
tail=temp;
}
}
打印链表
正序打印,倒序打印。
void print(struct List List){
nodes *temp=List.head;
while(temp->next!=NULL){
temp=temp->next;
cout<<temp->data<<" ";
}
cout<<endl;
while(temp!=List.head){
cout<<temp->data<<" ";
temp=temp->last;
}
}