设计模式技巧笔记

如何构建可变长度的列表

1. 使用链表

ignore…

2. 基于 realloc 队列

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
typedef struct _Item {
int a;
char b;
} Item;
typedef struct _ItemList {
unsigned int size; // current items count
unsigned int capacity; // max items
Item *items; // choice-1
Item **item_ptrs; //choice-2
} ItemList;
ItemList *NewItemList() {
ItemList *itemlist_tmp = (ItemList *)malloc(sizeof(ItemList));
itemlist_tmp->capacity = 4;
itemlist_tmp->items = (Item *)malloc(sizeof(Item) * itemlist_tmp->capacity);
if(!itemlist_tmp->items) {
return NULL;
}
itemlist_tmp->item_ptrs = (Item **)malloc(sizeof(Item *) * itemlist_tmp->capacity);
if(!itemlist_tmp->item_ptrs) {
return NULL;
}
return itemlist_tmp;
}
bool ItemListAdd(ItemList *itemlist, Item *item) {
if(!itemlist)
return false;
if(itemlist->size >= itemlist->capacity) {
Item **item_ptrs_tmp = (Item **)realloc(itemlist->item_ptrs, sizeof(Item *) * itemlist->capacity * 2);
if(!item_ptrs_tmp)
return false;
itemlist->item_ptrs = item_ptrs_tmp;
itemlist->capacity = itemlist->capacity * 2;
}
itemlist->item_ptrs[itemlist->size++] = item;
return true;
}
Item *ItemListNew(ItemList *itemlist) {
if(!itemlist)
return NULL;
if(itemlist->size >= itemlist->capacity) {
Item *items_tmp = (Item *)realloc(itemlist->items, sizeof(Item) * itemlist->capacity * 2);
if(!items_tmp)
return NULL;
itemlist->items = items_tmp;
itemlist->capacity = itemlist->capacity * 2;
}
return &(itemlist->items[itemlist->size++]);
}
void ItemInitlization() {
// do something initlizaiton, may be not in this function.
}