forked from garyexplains/examples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedlist.c
57 lines (53 loc) · 1.51 KB
/
linkedlist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
typedef struct element {
int value;
struct element *next;
} element;
element *insert_ordered(element *head, int v) {
if((head == NULL) || (head->value > v)){
// Empty list or need to insert at start
element *ne = malloc(sizeof(element));
ne->value = v;
ne->next = head;
return ne;
}
element *p = head;
while( (p->next != NULL) && (p->next->value < v) ) {
p = p->next;
}
// Now p points to place to insert new element
element *ne = malloc(sizeof(element));
ne->value = v;
ne->next = p->next;
p->next = ne;
return head;
}
void print_list(element *head) {
printf("List: ");
element *p = head;
while(p != NULL) {
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
int main() {
element *head = NULL;
head = insert_ordered(head, 7);
print_list(head);
head = insert_ordered(head, 10);
print_list(head);
head = insert_ordered(head, 20);
print_list(head);
head = insert_ordered(head, 15);
print_list(head);
head = insert_ordered(head, 4);
print_list(head);
head = insert_ordered(head, 30);
print_list(head);
head = insert_ordered(head, 29);
print_list(head);
head = insert_ordered(head, 5);
print_list(head);
}