aboutsummaryrefslogtreecommitdiff
path: root/data_structures/chapter_3/linked_list.c
blob: 920be0de9a25e300059e99532056441f92f318a4 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <stdio.h>
#include <stdlib.h>

#include "linked_list.h"

struct node
{
    elem data;
    position next;
};

int is_empty(list header)
{
    return header->next == NULL;
}

int is_last(position p, list header)
{
    return p->next == NULL;
}

position find(elem x, list header)
{
    position p;
    p = header->next;

    for(; p != NULL; p = p->next) {
        if(p->data == x) return p;
    }

    return NULL;
}

void delete(elem x, list header)
{
    position tmp;
    position pre;

    pre = find_previous(x, header);

    if(!is_last(pre, header)) {
        tmp = pre->next;
        pre->next = pre->next->next;
        free(tmp);
    }

}

position find_previous(elem x, list header)
{
    position p;

    p = header;
    while(p->next != NULL && p->next->data != x)
        p = p->next;

    return p;
}

void insert(elem x, list header, position p)
{
    position tmp;
    
    tmp = malloc(sizeof(struct node));
    
    if(tmp == NULL)
       printf("Out of space!\n"); 

    tmp->data = x;
    tmp->next = p->next;
    p->next = tmp;
}

void delete_list(list header)
{
    position p, tmp;

    p = header->next;
    header->next = NULL;

    while(p != NULL) {
        tmp = p;
        p = p->next;
        free(tmp);
    }
}

void print_list(list header)
{
    position p;

    if(is_empty(header))
       printf("empty list! \n");

    p = header->next;
    for(; p != NULL; p = p->next) 
        printf("%d->", p->data);
    printf("\n");
}

int test()
{
    position p1, p2, p3;
    list l1, l2, l3, l4;
    l1 = malloc(sizeof(struct node));
    l1->next == NULL;

    print_list(l1);

    /* test insert foo */
    insert(5, l1, l1);
    insert(4, l1, l1);
    insert(3, l1, l1);
    insert(2, l1, l1);
    insert(1, l1, l1);
    print_list(l1);


    /* test find foo */
    p1 = find(2, l1);
    printf("%d\n", p1->next->data);

    /* test delete foo */
    delete(3, l1);
    delete(5, l1);
    delete(1, l1);
    print_list(l1);

    /* test delete_list foo */
    delete_list(l1);
    print_list(l1);
}

int main()
{
    test();
    return 0;
}