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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
/* A small List class HTList.c
** ==================
**
** A list is represented as a sequence of linked nodes of type HTList.
** The first node is a header which contains no object.
** New nodes are inserted between the header and the rest of the list.
*/
#include "HTList.h"
#include <stdio.h> /* joe@athena, TBL 921019 */
HTList * HTList_new NOARGS
{
HTList *newList = (HTList *)malloc (sizeof (HTList));
if (newList == NULL) outofmem(__FILE__, "HTList_new");
newList->object = NULL;
newList->next = NULL;
return newList;
}
void HTList_delete ARGS1(HTList *,me)
{
HTList *current;
while ((current = me)) {
me = me->next;
free (current);
}
}
void HTList_addObject ARGS2(HTList *,me, void *,newObject)
{
if (me) {
HTList *newNode = (HTList *)malloc (sizeof (HTList));
if (newNode == NULL) outofmem(__FILE__, "HTList_addObject");
newNode->object = newObject;
newNode->next = me->next;
me->next = newNode;
}
else {
if (TRACE) fprintf(stderr,
"HTList: Trying to add object %p to a nonexisting list\n",
newObject);
abort();
}
}
BOOL HTList_removeObject ARGS2(HTList *,me, void *,oldObject)
{
if (me) {
HTList *previous;
while (me->next) {
previous = me;
me = me->next;
if (me->object == oldObject) {
previous->next = me->next;
free (me);
return YES; /* Success */
}
}
}
return NO; /* object not found or NULL list */
}
void * HTList_removeLastObject ARGS1 (HTList *,me)
{
if (me && me->next) {
HTList *lastNode = me->next;
void * lastObject = lastNode->object;
me->next = lastNode->next;
free (lastNode);
return lastObject;
} else /* Empty list */
return NULL;
}
void * HTList_removeFirstObject ARGS1 (HTList *,me)
{
if (me && me->next) {
HTList * prevNode;
void *firstObject;
while (me->next) {
prevNode = me;
me = me->next;
}
firstObject = me->object;
prevNode->next = NULL;
free (me);
return firstObject;
} else /* Empty list */
return NULL;
}
int HTList_count ARGS1 (HTList *,me)
{
int count = 0;
if (me)
while ((me = me->next))
count++;
return count;
}
int HTList_indexOf ARGS2(HTList *,me, void *,object)
{
if (me) {
int position = 0;
while ((me = me->next)) {
if (me->object == object)
return position;
position++;
}
}
return -1; /* Object not in the list */
}
void * HTList_objectAt ARGS2 (HTList *,me, int,position)
{
if (position < 0)
return NULL;
if (me) {
while ((me = me->next)) {
if (position == 0)
return me->object;
position--;
}
}
return NULL; /* Reached the end of the list */
}
|