尾插建立单链表C语言
时间: 2023-11-08 08:03:53 浏览: 37
下面是一个简单的例子,用C语言建立一个单链表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建新节点
struct ListNode* createNode(int val) {
struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
// 插入新节点
void insertNode(struct ListNode** head, struct ListNode* node) {
if (*head == NULL) {
*head = node;
return;
}
struct ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
// 打印链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
}
int main() {
// 创建链表
struct ListNode *head = NULL;
insertNode(&head, createNode(1));
insertNode(&head, createNode(2));
insertNode(&head, createNode(3));
insertNode(&head, createNode(4));
insertNode(&head, createNode(5));
// 打印链表
printList(head);
return 0;
}
```
这个例子中,我们定义了一个 `ListNode` 结构体来表示链表的节点,其中包含一个整数值 `val` 和一个指向下一个节点的指针 `next`。然后我们定义了三个函数来创建节点、插入节点和打印链表。在 `main` 函数中,我们创建了一个空链表,并插入了五个节点,最后打印整个链表。