怎么用C语言创建单链表
使用C语言创建单链表的基本步骤如下:
- 定义一个结构体来表示链表的节点,该结构体包含两个成员:数据域和指针域。
struct Node {
int data;
struct Node* next;
};
- 创建一个头节点,并将其指针域初始化为NULL。
struct Node* head = NULL;
- 定义一个函数来向链表中插入新节点。该函数接受一个整数作为参数,将其存储在新节点的数据域中,并将新节点插入到链表的末尾。
void insert(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
- 定义一个函数来遍历并打印链表中的所有节点。
void printList() {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
- 编写主函数,调用上述函数来创建、插入和打印链表。
int main() {
insert(1);
insert(2);
insert(3);
printList();
return 0;
}
以上代码将创建一个包含3个节点的单链表,并输出节点的值。输出结果为:1 2 3。你可以在此基础上进一步扩展链表的功能,比如插入、删除和查找节点等操作。
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。