要建立一個雙向鏈表,需要定義一個包含兩個指針(指向前一個節點和后一個節點)和數據的結構體。然后按照以下步驟進行建立:
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
struct Node* tail = NULL;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
注意更新新節點和尾部節點的指針。完整的示例代碼如下:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
void insert(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
void display() {
struct Node* current = head;
if (head == NULL) {
printf("List is empty.\n");
return;
}
printf("Nodes in the doubly linked list: \n");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
head = NULL;
tail = NULL;
insert(1);
insert(2);
insert(3);
display();
return 0;
}
這個示例代碼創建了一個包含三個節點(1,2,3)的雙向鏈表,并打印出節點的值。輸出結果為:Nodes in the doubly linked list: 1 2 3