用c语言写一个循环生成单链表的函数
时间: 2023-03-28 22:04:54 浏览: 56
可以使用以下代码来循环生成单链表:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* createList(int n) {
Node *head = NULL, *tail = NULL;
int i;
for (i = 1; i <= n; i++) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = i;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
int main() {
int n;
printf("Enter the number of nodes: ");
scanf("%d", &n);
Node *head = createList(n);
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return ;
}
```