c语言双向链表插入和删除完整代码
时间: 2023-09-16 22:06:36 浏览: 184
用c语言完成一个双向链表的创建,插入,删除
以下是双向链表的插入和删除完整代码示例,包括头插法、尾插法、指定位置插入和删除等操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 双向链表节点结构体
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 双向链表结构体
typedef struct List {
int length;
struct Node* head;
struct Node* tail;
} List;
// 初始化双向链表
void initList(List* list) {
if (list == NULL) {
return;
}
list->length = 0;
list->head = NULL;
list->tail = NULL;
}
// 创建双向链表节点
Node* createNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
if (node == NULL) {
return NULL;
}
node->data = data;
node->prev = NULL;
node->next = NULL;
return node;
}
// 头插法插入节点
void insertAtHead(List* list, int data) {
Node* node = createNode(data);
if (list->head == NULL) {
list->head = node;
list->tail = node;
} else {
node->next = list->head;
list->head->prev = node;
list->head = node;
}
list->length++;
}
// 尾插法插入节点
void insertAtTail(List* list, int data) {
Node* node = createNode(data);
if (list->tail == NULL) {
list->head = node;
list->tail = node;
} else {
node->prev = list->tail;
list->tail->next = node;
list->tail = node;
}
list->length++;
}
// 在指定位置插入节点
void insertAtIndex(List* list, int index, int data) {
if (index < 0 || index > list->length) {
return;
}
if (index == 0) {
insertAtHead(list, data);
return;
}
if (index == list->length) {
insertAtTail(list, data);
return;
}
Node* node = createNode(data);
Node* cur = list->head;
for (int i = 0; i < index - 1; i++) {
cur = cur->next;
}
node->prev = cur;
node->next = cur->next;
cur->next->prev = node;
cur->next = node;
list->length++;
}
// 删除头节点
void deleteAtHead(List* list) {
if (list->head == NULL) {
return;
}
Node* node = list->head;
list->head = node->next;
if (list->head != NULL) {
list->head->prev = NULL;
} else {
list->tail = NULL;
}
free(node);
list->length--;
}
// 删除尾节点
void deleteAtTail(List* list) {
if (list->tail == NULL) {
return;
}
Node* node = list->tail;
list->tail = node->prev;
if (list->tail != NULL) {
list->tail->next = NULL;
} else {
list->head = NULL;
}
free(node);
list->length--;
}
// 删除指定位置节点
void deleteAtIndex(List* list, int index) {
if (index < 0 || index >= list->length) {
return;
}
if (index == 0) {
deleteAtHead(list);
return;
}
if (index == list->length - 1) {
deleteAtTail(list);
return;
}
Node* cur = list->head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
free(cur);
list->length--;
}
// 打印双向链表
void printList(List* list) {
if (list == NULL || list->head == NULL) {
return;
}
Node* cur = list->head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main() {
List* list = (List*)malloc(sizeof(List));
initList(list);
insertAtHead(list, 1);
insertAtTail(list, 5);
insertAtIndex(list, 1, 3);
printList(list);
deleteAtHead(list);
deleteAtIndex(list, 1);
printList(list);
free(list);
return 0;
}
```
注意:在使用完毕后,需要手动释放双向链表和节点的内存空间,否则会造成内存泄漏。
阅读全文