C语言双向链表如何实现向指定索引位置插入元素

本文详细介绍了如何在C语言中使用双向链表结构实现插入操作,包括在链表头部、尾部以及指定索引处插入节点的函数,并提供了示例代码和功能函数如创建、删除和遍历链表。

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

核心代码:

int insertDoubleLinkedList(DoubleLinkedList *list, int index, int value) {
   
   
    if (list == NULL || list->head == NULL || list->tail == NULL) {
   
   
        return -1;
    }
    // 当一个元素都没有的时候,或者index=size的时候,是支持插入的
    if (index < 0 || index > list->size) {
   
   
        return -1;
    }
    // 创建节点
    DoubleLinkedListNode *newNode = newDoubleLinkedListNode(value);

    // 元素个数增加
    list->size++;

    // 插入到头部
    if (index == 0) {
   
   
        DoubleLinkedListNode *oldNode = list->head->next;
        list->head->next = newNode;
        newNode->prev = list->head;
        newNode->next = oldNode;
        oldNode->prev = newNode;
        return 0;
    }

    // 插入到尾部
    if (index == list->size) {
   
   
        DoubleLinkedListNode *oldNode = list->tail->prev;
        oldNode->next = newNode;
        newNode->prev = oldNode;
        newNode->next = list->tail;
        list->tail->prev = newNode;
        return list->size;
    }

    // 插入到中间
    int i = 0;
    DoubleLinkedListNode *current = list->head->next;
    while (i < index) {
   
   
        i++;
        current = current->next;
    }

    // 此时,current就是索引位置的节点,将该节点往后移动
    DoubleLinkedListNode *oldPrev = current->prev;
    oldPrev->next = newNode;
    newNode->prev = oldPrev;
    newNode->next = current;
    current->prev = newNode;

    // 返回
    return index;
}

double_linked_list.h

#ifndef ZDPC_ALGORITHM_DEV_DOUBLE_LINKED_LIST_H
#define ZDPC_ALGORITHM_DEV_DOUBLE_LINKED_LIST_H

// 公共头文件
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

// 双向链表的节点
typedef struct doubleLinkedListNode {
   
   
    int data;
    struct doubleLinkedListNode *next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源滚滚AI Python私教10年

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值