-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathlist.c
53 lines (47 loc) · 1.48 KB
/
list.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
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
/* your list function definitions */
void list_insert(int value, struct node **head) { // Insert new value into sorted ascending list
struct node *new_node = malloc(sizeof(struct node));
new_node -> value = value;
int temp = 0;
struct node fake_head = {0, *head}; // ensure inserting before *head works
struct node *curr_node = *head;
struct node *prev_node = &fake_head;
while (curr_node != NULL) {
temp = curr_node -> value;
if (value <= temp) { // if value bigger than curr node then move on. otherwise insert
new_node -> next = curr_node;
prev_node -> next = new_node;
*head = fake_head.next;
return;
}
prev_node = curr_node;
curr_node = prev_node -> next;
}
// value is bigger than everything in list. insert at the end
new_node -> next = NULL;
prev_node -> next = new_node;
*head = fake_head.next;
}
// Free memory used by the list
void free_list(struct node **head) {
struct node *next = NULL;
struct node *temp = *head;
while (temp != NULL) {
next = temp -> next;
free(temp);
temp = next;
}
free(head);
}
void print_list(struct node **head) {
printf("** List Contents Begin **\n");
struct node *temp = *head;
while (temp != NULL) {
printf("%d\n", temp -> value);
temp = temp -> next;
}
printf("** List Contents End **\n");
}