【发布时间】:2021-12-02 08:22:27
【问题描述】:
系统提示我创建一个生成数字 0-50 的链表。当列表生成 49 时,它应该打印出列表而不是打印 49。我的问题是试图弄清楚如何制作循环,以便它可以实际执行此任务。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printList();
struct Node {
int data;
struct Node* next;
};
int main() {
srand(time(0)); //srand sets starting value for series of random ints
int x = rand()%50 + 1; //gets random number in range 1-50, including 50
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->data = x; //assigns head to the random value between 0 and 50
head->next = NULL;
printList(head); //calls funtion to print list
return 0;
}
void printList (struct Node* n){
while (n != NULL){
printf(" %d ", n->data);
n = n->next;
}
}
【问题讨论】:
-
“如何制作循环”
for (i=0; i < 50; i++)?请澄清您对“制作循环”的哪个特定部分有困难? -
@kaylum 我不确定循环的条件是什么,因为我假设列表会一直持续下去,直到生成数字 49 为止。跨度>
-
我明白了。抱歉,我将您的问题误解为“直到生成 49 个数字”。我看到一个答案已经发布,看起来不错。
标签: c loops linked-list iteration random-seed