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
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
static struct _list *add_list(int val, struct _list *next) {
struct _list *list = (struct _list *)malloc(sizeof(struct _list));
list->val = val;
list->next = next;
return list;
}
int insert_val(struct _list **head, int val, int index) {
struct _list *curr = *head, *prev;
if (curr == NULL) {
if (index > 0) return FALSE;
*head = add_list(val, NULL);
return TRUE;
}
if (index == 0) {
*head = add_list(val, curr);
return TRUE;
}
int i;
for (i = 0; (index < 0 || i < index) && curr != NULL; i++)
prev = curr, curr = curr->next;
if (index > 0 && i != index) return FALSE;
prev->next = add_list(val, curr);
return TRUE;
}
int delete_list_at(struct _list **head, int index) {
struct _list *curr = *head, *prev;
if (curr == NULL) return FALSE;
int i;
for (i = 0; i < index && curr != NULL; i++)
prev = curr, curr = curr->next;
if (curr == NULL || i != index) return FALSE;
if (i == 0) *head = curr->next;
else prev->next = curr->next;
free(curr);
return TRUE;
}
void show_list(struct _list *list) {
if (list == NULL) return;
printf("%5d", list->val);
show_list(list->next);
}
void free_list(struct _list *list) {
if (list == NULL) return;
free_list(list->next);
free(list);
}