- 单向链表:
-
定义一个单向链表的节点结构体 Node,包含一个整型数据 data 和一个指向下一个节点的指针 next。
-
insert 函数用于在链表的末尾插入新节点。首先创建一个新的节点,并将传入的数据赋值给新节点的 data 字段。如果链表为空,则将新节点设置为头节点。否则,遍历链表找到最后一个节点,然后将新节点插入到最后一个节点的后面。
-
printList 函数用于打印链表中所有节点的数据。它从头节点开始遍历链表,依次打印每个节点的数据。
-
在 main 函数中,首先将头节点初始化为 NULL,然后使用 insert 函数向链表插入节点,并使用 printList 函数打印链表的内容。
#include <stdio.h> #include <stdlib.h> // 单向链表节点结构 typedef struct Node { int data; // 节点数据 struct Node* next; // 指向下一个节点的指针 } Node; // 在链表末尾插入新节点 void insert(Node** head, int data) { // 创建新节点 Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; // 如果链表为空,将新节点设置为头节点 if (*head == NULL) { *head = newNode; return; } // 遍历链表找到最后一个节点 Node* current = *head; while (current->next != NULL) { current = current->next; } // 将新节点插入到最后一个节点的后面 current->next = newNode; } // 打印链表中的所有节点数据 void printList(Node* head) { Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } int main() { Node* head = NULL; // 向链表插入节点 insert(&head, 1); insert(&head, 2); insert(&head, 3); // 打印链表 printList(head); return 0; }
-
- 双向链表:
-
定义了一个双向链表的节点结构体
Node
,与单向链表相比,每个节点还包含一个指向前一个节点的指针prev
。 -
insert
函数与单向链表的实现类似,区别在于每个新节点需要设置prev
指针,指向当前链表中的最后一个节点。 -
printList
函数也与单向链表的实现相同,从头节点开始遍历链表,并打印每个节点的数据。 -
在
main
函数中,首先将头节点初始化为NULL
,然后使用insert
函数向链表插入节点,并使用printList
函数打印链表的内容。 -
双向链表相比于单向链表的优势在于它可以在常数时间内进行逆向遍历,因为每个节点都有一个指向前一个节点的指针。
-
#include <stdio.h>
#include <stdlib.h>
// 双向链表节点结构
typedef struct Node {
int data; // 节点数据
struct Node* prev; // 指向前一个节点的指针
struct Node* next; // 指向下一个节点的指针
} Node;
// 在链表末尾插入新节点
void insert(Node** head, int data) {
// 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
// 如果链表为空,将新节点设置为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 遍历链表找到最后一个节点
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
// 将新节点插入到最后一个节点的后面
current->next = newNode;
newNode->prev = current;
}
// 打印链表中的所有节点数据
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 向链表插入节点
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
// 打印链表
printList(head);
return 0;
}