核心代码:
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