要建立一个双向链表,需要定义一个包含两个指针(指向前一个节点和后一个节点)和数据的结构体。然后按照以下步骤进行建立:
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