如何创建一个生成随机数的链表,直到它生成一个特定的数字
How to create a linked list that generates random numbers until it generates a specific number
系统提示我创建一个生成数字 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;
}
}
int rnd;
while((rnd = rand() % 50) != 49)
{
add_tolist(rnd);
}
printlist();
系统提示我创建一个生成数字 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;
}
}
int rnd;
while((rnd = rand() % 50) != 49)
{
add_tolist(rnd);
}
printlist();