用c语言写一个单链表并输出单链表
时间: 2023-05-22 07:01:59 浏览: 56
以下是用 C 语言编写单链表并输出的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 创建新节点
ListNode* createNode(int val) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 插入节点到链表尾部
void insertNode(ListNode **head, int val) {
ListNode *node = createNode(val);
if (*head == NULL) {
*head = node;
return;
}
ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
// 输出链表
void printList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
return 0;
}
```
输出结果为:
```
1 2 3
```
希望能对您有所帮助!