数据结构(C语言第二版)双链表的创建

上一篇文章我们创建了单链表,这篇文章我将分享在单链表的基础上改为双链表。

思路:

在定义结构体节点时新增一个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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值