#include #include #include struct node { struct node *next; int data; }; // Insert a new node into a sorted linked list, maintaining // the sorted order // 3 7 10 16 (insert 8)..... 3 7 8 10 16 struct node *insert_sorted(struct node *head, int number) { // PUT YOUR CODE HERE, REMEMBER TO CHANGE // THE RETURN struct node *current = head; struct node *previous = NULL; // Creates the new node ready for insertion struct node *new_node = malloc(sizeof(struct node)); new_node->data = number; new_node->next = NULL; // First edge case: empty list if (current == NULL) { head = new_node; return head; } // 3, 7, 10, 16 // insert 8 // go through the list and find where to insert // current->data < 8 while (current != NULL && current->data < number) { previous = current; current = current->next; } // either current = NULL which means I am at teh end // or I am at a place to insert if (previous == NULL) { new_node->next = head; head = new_node; } else { previous->next = new_node; new_node->next = current; } return head; } // DO NOT CHANGE THE CODE BELOW struct node *strings_to_list(int len, char *strings[]); void print_list(struct node *head); int main(int argc, char *argv[]) { int value; scanf("%d", &value); // create linked list from command line arguments struct node *head = NULL; if (argc > 1) { // list has elements head = strings_to_list(argc - 1, &argv[1]); } struct node *new_head = insert_sorted(head, value); print_list(new_head); return 0; } // create linked list from array of strings struct node *strings_to_list(int len, char *strings[]) { struct node *head = NULL; int i = len - 1; while (i >= 0) { struct node *n = malloc(sizeof (struct node)); assert(n != NULL); n->next = head; n->data = atoi(strings[i]); head = n; i -= 1; } return head; } // print linked list void print_list(struct node *head) { printf("["); struct node *n = head; while (n != NULL) { // If you're getting an error here, // you have returned an invalid list printf("%d", n->data); if (n->next != NULL) { printf(", "); } n = n->next; } printf("]\n"); }