使用C语言生成一个链表结构体
时间: 2024-10-14 21:14:43 浏览: 37
在C语言中,链表是一种常用的数据结构,它由一系列节点组成,每个节点包含数据域和指向下一个节点的指针。创建一个简单的单向链表结构体可以按照以下步骤:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点的函数
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node)); // 分配内存
if (newNode != NULL) { // 如果分配成功
newNode->data = value;
newNode->next = NULL; // 初始化新节点的next指针为NULL(表示该节点是最后一个)
return newNode;
}
printf("Memory allocation failed.\n"); // 内存分配失败的处理
return NULL;
}
// 插入节点到链表中的函数
void insertNode(Node** head, int value) {
Node* newNode = createNode(value); // 创建新节点
if (newNode != NULL) { // 新节点存在
if (*head == NULL) { // 链表为空,将新节点设置为首节点
*head = newNode;
} else { // 链表非空
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode; // 将新节点添加到链表尾部
}
}
}
// 打印链表的函数
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
insertNode(&head, 5);
insertNode(&head, 10);
insertNode(&head, 15);
printf("链表内容:\n");
printList(head);
return 0;
}
```
在这个例子中,我们首先定义了一个`Node`结构体,然后创建了插入节点和打印链表的方法。`main()`函数展示了如何使用这些功能来构建和操作链表。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)