Lab Description In this lab you will write a program to crea
Lab Description:
In this lab, you will write a program to create and manipulate a simple linked list. For each node in the linked list you will generate a random number, create a node that holds that number, and insert that node into its sorted position in the linked list. Once the nodes are inserted, you will traverse the list, printing the value held in each node. Then you will clean up the list (deleting all the nodes) and exit the program. You will also learn about a tool that you can use to help you check for memory errors in your code.
Lab Specifications:
Testing using Valgrind:
Once you have your program working, use valgrind with the
option to check for and correct any issues that are flagged. Don\'t forget to use the -g and -O0 (that\'s oh-zero) options. Modify your Makefile so that it compiles with those options automatically
Make sure that the Heap, Leak and Error Summaries using valgrind show that there are no errors or issues.
Solution
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int number;
struct ListNode* next;
};
void printList(struct ListNode *head)
{
while(head != NULL)
{
printf(\"%d \", head->number);
head = head->next;
}
}
void deleteList(struct ListNode *head)
{
struct ListNode* temp = head;
while(temp != NULL)
{
head = head->next;
free(temp);
temp = head;
}
}
void insertNodeSorted(struct ListNode** head, int data)
{
struct ListNode* node =(struct ListNode*) malloc(sizeof(struct ListNode));
struct ListNode* temp;
node->number = data;
node->next = NULL;
if (*head == NULL)
{
node->next = *head;
*head = node;
}
else if ((*head)->number >= data)
{
node->next = *head;
*head = node;
}
else
{
temp = *head;
for(;temp->next!=NULL &&
temp->next->number < data; temp = temp->next);
node->next = temp->next;
temp->next = node;
}
}
int main(int argc, char *argv[]) {
struct ListNode* head = NULL;
int a = atoi(argv[1]);
printf(\"%d\ \",a);
int i=0;
srand(0);
printf(\"Random Numbers are\ \");
for(i=0;i<a;++i)
{
int r = rand()%(a+1);
printf(\"%d \",r);
insertNodeSorted(&head, r);
}
printf(\"\ \");
printf(\"List in Sorted Manner\ \");
printList(head);
deleteList(head);
return 0;
}

