#include #include // 定義節點結構 typedef struct Node { int data; struct Node* prev; struct Node* next; } Node; // 定義雙向鏈結串列結構 typedef struct { Node* head; Node* tail; } DoublyLinkedList; // 初始化雙向鏈結串列 void initList(DoublyLinkedList* list) { list->head = NULL; list->tail = NULL; } // 在尾部插入新節點 void insertAtTail(DoublyLinkedList* list, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; if (list->tail == NULL) { newNode->prev = NULL; list->head = newNode; list->tail = newNode; } else { newNode->prev = list->tail; list->tail->next = newNode; list->tail = newNode; } } // 從頭到尾遍歷並印出串列 void printListForward(DoublyLinkedList* list) { Node* current = list->head; printf("從頭到尾: "); while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } // 從尾到頭遍歷並印出串列 void printListBackward(DoublyLinkedList* list) { Node* current = list->tail; printf("從尾到頭: "); while (current != NULL) { printf("%d ", current->data); current = current->prev; } printf("\n"); } // 主函數示例 int main() { DoublyLinkedList list; initList(&list); insertAtTail(&list, 10); insertAtTail(&list, 20); insertAtTail(&list, 30); printListForward(&list); printListBackward(&list); return 0; }