1. #include <stdio.h>
    2. #include <stdlib.h>
    3. // 双向链表节点定义
    4. typedef struct Node {
    5. int data;
    6. struct Node *prev;
    7. struct Node *next;
    8. } Node;
    9. // 创建新节点
    10. Node* createNode(int data) {
    11. Node* newNode = (Node*)malloc(sizeof(Node));
    12. if (newNode == NULL) {
    13. printf("Memory allocation failed\n");
    14. exit(1);
    15. }
    16. newNode->data = data;
    17. newNode->prev = NULL;
    18. newNode->next = NULL;
    19. return newNode;
    20. }
    21. // 在链表末尾插入节点
    22. void append(Node** headRef, int data) {
    23. Node* newNode = createNode(data);
    24. if (*headRef == NULL) {
    25. *headRef = newNode;
    26. return;
    27. }
    28. Node* current = *headRef;
    29. while (current->next != NULL) {
    30. current = current->next;
    31. }
    32. current->next = newNode;
    33. newNode->prev = current;
    34. }
    35. // 打印链表元素
    36. void printList(Node* head) {
    37. Node* current = head;
    38. printf("List: ");
    39. while (current != NULL) {
    40. printf("%d ", current->data);
    41. current = current->next;
    42. }
    43. printf("\n");
    44. }
    45. // 反向打印链表元素
    46. void reversePrintList(Node* head) {
    47. Node* current = head;
    48. if (current == NULL) {
    49. return;
    50. }
    51. // 移动到链表末尾
    52. while (current->next != NULL) {
    53. current = current->next;
    54. }
    55. printf("Reverse List: ");
    56. // 从末尾开始反向遍历并打印元素
    57. while (current != NULL) {
    58. printf("%d ", current->data);
    59. current = current->prev;
    60. }
    61. printf("\n");
    62. }
    63. // 释放链表内存
    64. void freeList(Node** headRef) {
    65. Node* current = *headRef;
    66. Node* next;
    67. while (current != NULL) {
    68. next = current->next;
    69. free(current);
    70. current = next;
    71. }
    72. *headRef = NULL;
    73. }
    74. int main() {
    75. Node* head = NULL;
    76. // 在链表末尾插入元素
    77. append(&head, 1);
    78. append(&head, 2);
    79. append(&head, 3);
    80. // 打印链表元素
    81. printList(head);
    82. // 反向打印链表元素
    83. reversePrintList(head);
    84. // 释放链表内存
    85. freeList(&head);
    86. return 0;
    87. }