数据结构与算法(双向链表)

本文介绍了一个简单的双向链表实现,包括创建、查询、删除及插入等基本操作,并提供了完整的C语言代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
//用户自定义双向链表
typedef struct node
{
    int num;
    struct node *prior;//前指针
    struct node *next;//后指针
}stud;

//指针函数
stud* create(int n)
{
    stud *p,*h,*s;
    int i;
    h=(stud*)malloc(sizeof(stud));
    h->num=0;
    h->next=h->prior=NULL;
    p=h;
    for(i=0;i<n;i++)
    {
        s=(stud*)malloc(sizeof(stud));
        p->next=s;
        s->num=rand()%100;
        s->prior=p;
        s->next=NULL;
        p=s; 
    } 
    p->next=NULL;
    return h;
}

stud* search(stud *h,int NumOfSearch)
{
    stud *p;
    p=h->next;
    while(p)
    {
        if(p->num==NumOfSearch) 
            return p;
        else 
            p=p->next;
    }
        printf("没有这个数据");
        return NULL;
}

void del(stud *p)
{
    p->prior->next=p->next;
    p->next->prior=p->prior;
    free(p);
} 

stud* insert(stud *h,int NumOfInsert,int NumOfAddr)
{
    stud *p,*Insertstruct;
    int i=1;//人类的正常思维1-2-3-4 
    p=h->next;
    while(p){
        if(i==NumOfAddr-1)//因为当执行这句语句时i==NumOfAddr那么就会在需求插入的后一位插入 
            break;
        else{
            i++;
            p=p->next;  
        }
    }
    Insertstruct=(stud*)malloc(sizeof(stud));
    Insertstruct->num=NumOfInsert;
    Insertstruct->next=p->next;
    p->next=Insertstruct; 
}

stud* display(stud *head)
{
    stud *p;
    p=head->next;
    while(p)
    {
        printf("%d\t",p->num);
        p=p->next;
    }
    printf("\n");
}

int main(void)
{
    stud *head,*NumOfDel;
    head=create(10);//创建双向链表
    display(head);

    NumOfDel=search(head,0);//查询数字为0的指针顺序
    del(NumOfDel);//删除
    display(head);

    insert(head,10,3);//在链表第三位插入数字10
    display(head);
}

接下来是执行效果这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值