上一篇文章我们创建了单链表,这篇文章我将分享在单链表的基础上改为双链表。
思路:
在定义结构体节点时新增一个piror指针指向前驱节点,之后在后边更新节点时,除了更新后继节点,还要更新前驱节点。
具体代码实现:
#include <stdio.h>
#include <stdlib.h>
//定义结构体
typedef struct Sqlist{
int data;
struct Sqlist* next;
struct Sqlist* prior;
}Sqlist;
//初始化双链表
Sqlist* initlist(){
Sqlist* head=(Sqlist*)malloc(sizeof(Sqlist));
head->next=NULL;
head->prior=NULL;
return head;
}
//插入
void Insertlist(Sqlist* L,int elem){
Sqlist* new_code = (Sqlist*)malloc(sizeof(Sqlist));
new_code->data=elem;
new_code->next=NULL;
new_code->prior=NULL;
Sqlist* temp=L;
while (temp->next!=NULL){
temp=temp->next;
}
temp->next=new_code;
new_code->prior=temp;
}
//查找
void Searchlist(Sqlist* L,int elem){
Sqlist* temp=L;
while(temp!=NULL){
if (elem==temp->data){
printf("已找到%d\n",temp->data);
return;
}
temp=temp->next;
temp->prior=L;
}
printf("查找失败,未找到该元素!");
}
//删除
Sqlist* Deletelist(Sqlist* L,int elem){
Sqlist* current=L->next;
Sqlist* temp=L;
while (current!=NULL){
current->prior->next=current->next;
if (elem==current->data){
temp->next=current->next;
if (current->next!=NULL){
current->next->prior=temp;
}
else {
current->prior=temp;
}
printf("删除%d成功\n",current->data);
free(current);
return L;
}
temp=current;
current=current->next;
}
printf("删除失败,未找到该元素");
return L;
};
//输出单链表
void Printlist(Sqlist* L){
if (L->next==NULL){
printf("链表为空");
return;
}
Sqlist* p=L->next;
printf("表内所有元素为:");
while ( p != NULL) {
printf("%d\t", p->data);
p = p->next;
}
}
//释放内存
void freelist(Sqlist* L){
Sqlist* temp=NULL;
while (L!=NULL){
temp=L;
L=L->next;
free(temp);
}
}
int main(){
Sqlist* list=initlist();
Insertlist(list,10);
Insertlist(list,90);
Searchlist(list,90);
Printlist(list);
freelist(list);
return 0;
}