#include <stdio.h>
#include <stdlib.h>
// 双向链表节点定义
typedef struct Node {
int data;
struct Node *prev;
struct Node *next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// 在链表末尾插入节点
void append(Node** headRef, int data) {
Node* newNode = createNode(data);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
Node* current = *headRef;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
// 打印链表元素
void printList(Node* head) {
Node* current = head;
printf("List: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 反向打印链表元素
void reversePrintList(Node* head) {
Node* current = head;
if (current == NULL) {
return;
}
// 移动到链表末尾
while (current->next != NULL) {
current = current->next;
}
printf("Reverse List: ");
// 从末尾开始反向遍历并打印元素
while (current != NULL) {
printf("%d ", current->data);
current = current->prev;
}
printf("\n");
}
// 释放链表内存
void freeList(Node** headRef) {
Node* current = *headRef;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*headRef = NULL;
}
int main() {
Node* head = NULL;
// 在链表末尾插入元素
append(&head, 1);
append(&head, 2);
append(&head, 3);
// 打印链表元素
printList(head);
// 反向打印链表元素
reversePrintList(head);
// 释放链表内存
freeList(&head);
return 0;
}