Sorted Insert
Completed
Read n integers and insert each into a linked list that is kept sorted ascending. Print the final list.
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
6 5 1 4 1 9 2
Output
1 1 2 4 5 9
Editor
C
Hints
Stop at the last node whose value is <= the new value, then splice the node in after it.
Solution explanation
Insertion into a sorted list is the linked-list version of insertion sort.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
struct Node *insert_sorted(struct Node *head, int value) {
struct Node *node = malloc(sizeof(struct Node));
node->value = value;
if (head == NULL || value < head->value) {
node->next = head;
return node;
}
struct Node *p = head;
while (p->next != NULL && p->next->value <= value) p = p->next;
node->next = p->next;
p->next = node;
return head;
}
int main() {
int n, x;
struct Node *head = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
head = insert_sorted(head, x);
}
for (struct Node *p = head; p != NULL; p = p->next) printf("%d ", p->value);
printf("\n");
return 0;
}