-
Notifications
You must be signed in to change notification settings - Fork 0
/
intlist.c
64 lines (64 loc) · 1.14 KB
/
intlist.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
#include <stdlib.h>
typedef struct IntList{
int val;
struct IntList * next;
int refcount;
}IntList;
IntList * allocateIntList(IntList * p){
static IntList * pool=NULL;
if (!p){
if (!pool){
IntList * p=(IntList*)malloc(sizeof(IntList)*1000);
for (int i=0;i<1000;i++){
p[i].next=pool;
pool=p+i;
}
}
p=pool;
p->refcount=1;
pool=pool->next;
return p;
}else{
p->next=pool;
pool=p;
return NULL;
}
}
IntList * retainIntList(IntList * p){ // p: stolen returns: new
if (p){
p->refcount++;
}
return p;
}
IntList * releaseIntList(IntList * p){ // p: consumed returns: NULL
if (p){
p->refcount--;
if (p->refcount==0){
if (p->next){
releaseIntList(p);
}
allocateIntList(p);
}
}
return NULL;
}
IntList * newIntList(int val,IntList * nxt){ // nxt: consumed returns: new
IntList * p=allocateIntList(NULL);
p->val=val;
p->next=nxt;
return p;
}
char * convertIntListToString(IntList * list){ // l: stolen returns: new
int l=0;
for (IntList * p=list;p;p=p->next){
l++;
}
char * s=(char*)malloc(l+1);
int i=0;
for (IntList * p=list;p;p=p->next){
s[i]=p->val;
i++;
}
s[i]=0;
return s;
}