双链表实现
双链表的每个节点包含指向前一个和后一个节点的指针。
#include <stdio.h>
#include <stdlib.h>typedef struct Node {int data;struct Node *prev; // 指向前一个节点struct Node *next; // 指向下一个节点
} Node;typedef struct {Node *head; // 头指针
} DoublyLinkedList;// 初始化双链表
void initList(DoublyLinkedList *list) {list->head = NULL;
}// 插入节点
void insert(DoublyLinkedList *list, int value) {Node *newNode = (Node *)malloc(sizeof(Node));newNode->data = value;newNode->prev = NULL;newNode->next = list->head;if (list->head != NULL) {list->head->prev = newNode;}list->head = newNode;
}// 打印链表
void printList(DoublyLinkedList *list) {Node *current = list->head;while (current != NULL) {printf("%d ", current->data);current = current->next;}printf("\n");
}// 释放链表
void freeList(DoublyLinkedList *list) {Node *current = list->head;while (current != NULL) {Node *temp = current;current = current->next;free(temp);}
}int main() {DoublyLinkedList list;initList(&list);insert(&list, 10);insert(&list, 20);insert(&list, 30);printList(&list);freeList(&list);return 0;
}