用c语言创建一个简单的单链表
时间: 2023-09-13 14:11:21 浏览: 51
以下是使用C语言创建一个简单的单链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(struct Node** head, struct Node* newNode) {
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insertNode(&head, createNode(1));
insertNode(&head, createNode(2));
insertNode(&head, createNode(3));
insertNode(&head, createNode(4));
insertNode(&head, createNode(5));
printf("Linked List: ");
printList(head);
return 0;
}
```
在这个例子中,我们定义了一个 `Node` 结构体来表示链表中的每个节点。然后,我们编写了一个 `createNode` 函数来创建一个新的节点,并返回该节点的指针。我们还编写了一个 `insertNode` 函数来将新节点插入到链表的末尾。最后,我们编写了一个 `printList` 函数来打印整个链表。
在 `main` 函数中,我们首先将空指针赋给 `head`,表示链表为空。然后,我们使用 `insertNode` 函数向链表中插入五个节点。最后,我们使用 `printList` 函数打印整个链表。