In: Computer Science
This is my C language code. I have some problems with the linked list. I can't store the current. After current = temp, I don't know how to move to the next node. current = current-> next keeps making current into NULL.
#include
#include
#include
#include
struct node{int data; struct node *next;};
int main()
{
struct node *head, *current, *temp, *trash;
srand(time(0));
int randNumber = rand()%51;
if(randNumber != 49)
{
temp = (struct node*)malloc(sizeof(struct node));
current = (struct node*)malloc(sizeof(struct node));
temp->data = randNumber;
temp->next = NULL;
head = temp;
head->next = current = NULL;
randNumber = rand()%51;
while(randNumber != 49)
{
temp = (struct node*)malloc(sizeof(struct node));
temp->data = randNumber;
temp->next = NULL;
current= temp;
current = current->next;
randNumber = rand()%51;
}
temp = head;
printf("%d", temp->data);
printf("%d", temp->next->data);
while (temp != NULL)
{
printf("%d\n", temp->data);
trash = temp;
temp = temp->next;
free(trash);
}
}
printf("EXIT\n");
return 0;
}
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
#include <stdio.h>
#include <stdlib.h>
struct node{int data; struct node *next;};
int main()
{
struct node *head, *current, *temp, *trash;
srand(time(0));
int randNumber = rand()%51;
if(randNumber != 49)
{
temp = (struct
node*)malloc(sizeof(struct node));
temp->data = randNumber;
temp->next = NULL;
head = temp;
head->next = NULL;
current = head;
randNumber = rand()%51;
while(randNumber != 49)
{
temp = (struct
node*)malloc(sizeof(struct node));
temp->data = randNumber;
temp->next = NULL;
current->next= temp;
current = temp;
randNumber =
rand()%51;
}
temp = head;
while (temp != NULL)
{
printf("%d\n", temp->data);
trash = temp;
temp = temp->next;
free(trash);
}
}
printf("EXIT\n");
return 0;
}