#include <stdio.h>
#include <stdlib.h>
// 双向链表节点定义
struct Node {
int data; // 节点存储的数据
struct Node* prev; // 指向前一个节点的指针
struct Node* next; // 指向后一个节点的指针
};
// 在链表末尾添加节点
void append(struct Node** head_ref, int new_data) {
// 创建新节点
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; // 用于遍历链表
// 设置新节点的数据和指针
new_node->data = new_data;
new_node->next = NULL;
// 如果链表为空,则设置新节点为头节点
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
// 找到最后一个节点
while (last->next != NULL) {
last = last->next;
}
// 将新节点添加为最后一个节点的后继节点
last->next = new_node;
new_node->prev = last;
}
// 遍历并打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL; // 创建一个空链表
// 在链表末尾添加节点
append(&head, 1);
append(&head, 2);
append(&head, 3);
// 遍历并打印链表
printList(head);
return 0;
}
C语言双向链表
最新推荐文章于 2025-03-07 16:30:53 发布