How would you in C programming using a Node struct and a Linkedlist struct take user integer inputs and store them in the linked list in numerical order and then print them in order?
#include<stdio.h>
#include<malloc.h>
typedef struct linkedlist_node_t {
int value;
linkedlist_node_t* next;
} linkedlist_node;
typedef struct linkedlist_t {
linkedlist_node* head;
} linkedlist;
/* Deletes all nodes in the given list. */
void delete_all (linkedlist* list)
{
/* Ensure the list is non-null. */
if (!list) return;
linkedlist_node* old_head;
while (list->head)
{
/* Copy the head pointer. */
old_head = list->head;
/* Make its next node the new head. */
list->head = old_head->next;
/* Release the old head*/
free (old_head);
}
/* The list is empty. */
list->head = 0;
}
/* Inserts the given value into the given linked list. */
linkedlist_node* insert_value (linkedlist* list, int value)
{
/* Ensure the list is non-null. */
if (!list) return 0;
/* Instantiate and initialise a new node. */
linkedlist_node* new_node = malloc (sizeof
(linkedlist_node));
new_node->value = value;
new_node->next = 0;
if (list->head==0)
{
/* If the list is empty (has no head), the new node becomes the
head. */
list->head = new_node;
}
else if (value<list->head->value)
{
/* Otherwise, if the value is less than the head's value,
insert the new node before the head node. The new node
becomes the head. */
new_node->next = list->head;
list->head = new_node;
}
else
{
/* Otherwise, traverse the list to find the insertion point
(the node that comes before the new node). */
linkedlist_node* node = list->head;
while (node->next &&
node->next->value<value)
node = node->next;
/* Insert the new node immediately after node. */
new_node->next = node->next;
node->next = new_node;
}
/* Return the new node (not essential, but good practice).
*/
return new_node;
}
/* Prints the given list. */
void print_list (linkedlist* list)
{
/* Ensure the list is non-null. */
if (!list) return;
/* Traverse the list from the head, printing each node on a new
line. */
linkedlist_node* n = list->head;
while (n)
{
printf ("%d\n", n->value);
n = n->next;
}
}
/* Test-drive the functions. */
int main()
{
/* Instantiate and initialise an empty list (no head). */
linkedlist list;
list.head = 0;
/* Insert values (in descending order). */
for (int v=0; v<10; ++v)
insert_value (&list, 10-v);
/* Print the list (in ascending order). */
print_list (&list);
/* Don't forget to release resources! */
delete_all (&list);
return 0;
}