-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.c
81 lines (47 loc) · 1.33 KB
/
link.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "link.h"
static Link *createLink(Node *node);
static void deleteLink(Link *link);
void addLink(Link *firstLink, Node *node) {
// case 1: first link is not in use
if (!firstLink) {
firstLink = createLink(node);
return;
}
Link *lastLink = firstLink;
do {
// case 2: there is already a link to this node
if (lastLink->node == node) {
lastLink->weight++;
return;
}
lastLink = lastLink->nextLink;
} while (lastLink->nextLink != NULL);
// case 3: there is no link to this node
lastLink->nextLink = createLink(node);
}
void removeLink(Link *firstLink, Node *node) {
Link *link = firstLink;
Link *nextLink = NULL;
Link *removedLink = NULL;
do {
nextLink = link->nextLink;
if (link->node == node) {
removedLink = link;
deleteLink(removedLink);
link = nextLink;
break;
}
link = nextLink;
nextLink = NULL;
} while (link->nextLink != NULL);
}
static Link *createLink(Node *node) {
Link *link = (Link *)malloc(sizeof(Link));
link->node = node;
link->nextLink = NULL;
link->weight = 1;
return link;
}
static void deleteLink(Link *link) {
free(link);
}