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
|
#include <iostream>
struct Information {
int a, b, c;
};
struct Node {
Information info;
Node *next;
};
struct List {
Node *head, *tail;
List() { head = tail = 0; }
};
void addItem(List *list, int x, int y, int z)
{
if (list->head == 0) // special case. for first item in the list.
{
list->head = new Node;
list->tail = list->head; // the only item is both first and last
}
else
{
list->tail->next = new Node;
list->tail = list->tail->next;
}
list->tail->info.a = x;
list->tail->info.b = y;
list->tail->info.c = z;
list->tail->next = 0;
}
void loopList(List *list, void (*cb)(Information))
{
Node *i = list->head;
while (i != 0)
{
cb(i->info);
i = i->next;
}
}
void printInformation(Information info)
{
std::cout << "a:" << info.a << " b:" << info.b << " c:" << info.c << std::endl;
}
int main(int argc, char *argv[])
{
List *lst = new List;
addItem(lst, 1, 2, 3);
addItem(lst, 22, 33, 77);
addItem(lst, 121, 343, 979);
loopList(lst, printInformation);
// free list
// deallocation code omitted
return 0;
}
| |