用c语言实现单链表,能输入元素
时间: 2023-05-14 21:04:13 浏览: 99
非常好的问题!以下是一个简单的 C 语言单链表实现,可以输入元素:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = (*head);
(*head) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
int n, data;
printf("请输入元素个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第 %d 个元素:", i + 1);
scanf("%d", &data);
insert(&head, data);
}
printf("单链表的元素为:");
printList(head);
return 0;
}
```
希望这个代码能够帮到你!
阅读全文