In: Computer Science
Create a program that generates random number between 0 and 50 and puts them into a linked list. When it generates 49, instead of adding it to the list, it prints the list, freeing each node and then exits. Submit your .c file
Code
#include <stdio.h>
#include <stdlib.h>
void sorted_ins(struct Node **,struct Node *);
struct Node
{
int value;
struct Node *next;
};
struct Node *head=NULL;
void add(struct Node **head,int v)
{
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->value=v;
struct Node *temp=*head;
if(*head==NULL) //if head is null create head
{
*head=node;
return;
}
while(temp->next!=NULL) //loop till the end,add element
{
temp=temp->next;
}
temp->next=node;
}
void print(struct Node** head)
{
struct Node *temp=*head;
while(temp!=NULL)
{
printf("%d ",temp->value);
temp=temp->next;
}
}
void freelist(struct Node** head)
{
struct Node* current=*head;
struct Node* next;
while(current!=NULL)
{
next=current->next;
free(current); //free the element
current=next;
}
*head=NULL; //assign head to null
}
int main ()
{
int i, n; time_t t;
struct Node *s=NULL;
int d;
/* Intializes random number generator */
srand((unsigned)time(&t)); /* Print 5 random numbers from 0 to 49 */
while(1)
{
d=rand()%50;
if(d==49) //if random value is 49 print the list and exit
{
print(&s);
freelist(&s);
break;
}
add(&s,d); //add element to the list if value is 49
}
return(0);
}
Terminal Work
.