双链表:
双向性:每个节点都包含两个指针,一个指向前一个节点(prev),一个指向后一个节点(next)。插入和删除操作比较灵活,时间复杂度为O(1)。但是随机访问的时间复杂度为O(n),需要从头节点或者尾节点开始顺序查找。适合于频繁进行插入和删除操作的场景。
代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data; // 数据域
struct Node* prev; // 指向前一个节点的指针
struct Node* next; // 指向下一个节点的指针
};
// 初始化双链表
void initDoubleList(struct Node** head) {
*head = NULL; // 将头指针置为空,表示链表为空
}
// 在双链表末尾添加节点
void appendDoubleNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
}
// 在双链表指定位置插入节点
void insertDoubleNode(struct Node** head, int data, int position) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (position == 0) {
newNode->next = *head;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
} else {
struct Node* temp = *head;
int count = 0;
while (temp != NULL && count < position - 1) {
temp = temp->next;
count++;
}
if (temp == NULL) {
printf("Invalid position\n");
return;
}
newNode->prev = temp;
newNode->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = newNode;
}
temp->next = newNode;
}
}
// 删除双链表指定位置的节点
void deleteDoubleNode(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
if (position == 0) {
*head = temp->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
} else {
int count = 0;
while (temp != NULL && count < position) {
temp = temp->next;
count++;
}
if (temp == NULL) {
printf("Invalid position\n");
return;
}
temp->prev->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
}
}
// 打印双链表
void printDoubleList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 释放双链表内存
void freeDoubleList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
struct Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
}
int main() {
struct Node* head;
initDoubleList(&head);
// 在双链表末尾添加节点
appendDoubleNode(&head, 10);
appendDoubleNode(&head, 20);
appendDoubleNode(&head, 30);
appendDoubleNode(&head, 40);
// 打印双链表
printf("Double List: ");
printDoubleList(head); // 输出: 10 20 30 40
// 在双链表指定位置插入节点
insertDoubleNode(&head, 25, 2);
// 打印双链表
printf("Double List after insertion: ");
printDoubleList(head); // 输出: 10 20 25 30 40
// 删除双链表指定位置的节点
deleteDoubleNode(&head, 3);
// 打印双链表
printf("Double List after deletion: ");
printDoubleList(head); // 输出: 10 20 25 40
// 释放双链表内存
freeDoubleList(head);
return 0;
}