Home > Software design >  How to create a linked list that generates random numbers until it generates a specific number
How to create a linked list that generates random numbers until it generates a specific number

Time:10-14

Im prompted to create a linked list that generates numbers 0-50. When the list generates 49, instead of printing 49 its supposed prints out the list. My issue is trying to figure out how to make the loop so it can actually perform this tasl.

#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;
    }
}

CodePudding user response:

int rnd;
while((rnd = rand() % 50) != 49)
{ 
    add_tolist(rnd);
}

printlist();
  • Related