|
Page 4 of 6
From original problem description, It is already known that there is data set of 50K intergers. Since we already know worst case scenario, isn't it possible to allocate memory space for 50K nodes and then manage/use allocated memory space to build three linked list? There are good advantages in using Array Based implementation. However, for some obvious reasons it may not be suitable for all software applications.
Array based implementation is to pre-allocate memory (by Array Declaration), and then have in-built memory management to allocate and de-allocate nodes from pre-allocated memory. Please note, that there exists a more flexible solution, called Pool Based Memory Allocation described/presented in Dynamic Memory Allocation Performance.
Similar to normal linked list implementation, a structure is defined to represent each node in Linked List. And a buffer array is declared to pre-allocate all memory.
typedef struct node_def {
int number;
struct node_def *next;
} node;
// Static Buffer Array Allocation
node buf_arr[5000];
Please note, at any given time, each Linked List and next pointer of each node will point to an element in buf_arr. A linked list can be viewed as following.
node* start;
start = &buf_arr[xxx];
start->next = &buf_arr[yyy];
Or
buf_arr[yyy].next = &buf_arr[yyy];
In-built memory manager also have to use a list, called free list. Free List contains list of all free nodes and during an allocation request, a node from start of Free List is removed and returned. During de-allocation, a node is added to end of Free List. At initialization, each node belongs to Free List and all other lists are going to be empty. Free List may be declared as shown below.
// Free List
node *freeSt, *freeEnd;
// Initialize Free List
void init_fl (void) {
int i;
// Initialize Free List
freeSt = &buf_arr[0];
freeEnd = &buf_arr[NUM-1];
buf_arr[NUM-1].next = NULL;
// Create Link for each element
for (i = 0; i < NUM-1; i++)
buf_arr[i].next = &buf_arr[i+1];
}
Please note Free List initialization function. Free List initialization is always required at program start.
|