在自增数组的基础上实现的,依赖C 实现泛型ArrayList数组。完成以下功能:
- 元素的入队出队
- 容量控制
- 移除指定位置元素
typedef struct
{
ArrayList arrayList[1];
/**
* ArrayQueue top element index
*/
int topIndex;
}
ArrayQueue;
typedef struct
{
ArrayQueue* (*Create) (int typeSize);
void (*Init) (int typeSize, ArrayQueue* outArrayQueue);
ArrayQueue* (*CreateWithCapacity)(int typeSize, int capacity);
void (*InitWithCapacity) (int typeSize, int capacity, ArrayQueue* outArrayQueue);
void (*Release) (ArrayQueue* arrayQueue);
/**
* Push element from elementPtr into ArrayQueue
*
* elementPtr point to element
* return elementPtr in ArrayQueue
*/
void* (*Push) (ArrayQueue* arrayQueue, void* elementPtr);
/**
* Pop element from ArrayQueue
* return top elementPtr in ArrayQueue, if no element return defaultValuePtr
*/
void* (*Pop) (ArrayQueue* arrayQueue, void* defaultValuePtr);
/**
* Remove element at index range in [topIndex, ArrayQueue size - 1]
*/
void (*RemoveAt) (ArrayQueue* arrayQueue, int index);
}
_AArrayQueue_;
extern _AArrayQueue_ AArrayQueue[1];
/** The type is the ArrayQueue value type */
#define ArrayQueue(valueType) ArrayQueue
static void* Push(ArrayQueue* arrayQueue, void* elementPtr)
{
if (arrayQueue->topIndex > arrayQueue->arrayList->array->length - arrayQueue->arrayList->size)
{
AArrayList->RemoveRange(arrayQueue->arrayList, 0, arrayQueue->topIndex - 1);
arrayQueue->topIndex = 0;
}
return AArrayList->Add(arrayQueue->arrayList, elementPtr);
}
static void* Pop(ArrayQueue* arrayQueue, void* defaultValuePtr)
{
ArrayList* arrayList = arrayQueue->arrayList;
if (arrayQueue->topIndex > arrayList->size - 1)
{
return defaultValuePtr;
}
return (char*) arrayList->array->data + arrayList->typeSize * (arrayQueue->topIndex++);
}
static void RemoveAt(ArrayQueue* arrayQueue, int index)
{
ArrayList* arrayList = arrayQueue->arrayList;
ALog_A
(
index >= arrayQueue->topIndex && index < arrayList->size,
"popIndex index = %d, out of range [%d, %d]",
index, arrayQueue->topIndex, arrayList->size - 1
);
AArrayList->Remove(arrayList, index);
}
static void Release(ArrayQueue* arrayQueue)
{
arrayQueue->topIndex = 0;
AArrayList->Release(arrayQueue->arrayList);
}
static void InitWithCapacity(int typeSize, int capacity, ArrayQueue* outArrayQueue)
{
if (capacity == 0)
{
AArrayList->Init(typeSize, outArrayQueue->arrayList);
}
else
{
AArrayList->InitWithCapacity(typeSize, capacity, outArrayQueue->arrayList);
}
outArrayQueue->topIndex = 0;
}
static ArrayQueue* CreateWithCapacity(int typeSize, int capacity)
{
ArrayQueue* arrayQueue = (ArrayQueue*) malloc(sizeof(ArrayQueue));
InitWithCapacity(typeSize, capacity, arrayQueue);
return arrayQueue;
}
static void Init(int typeSize, ArrayQueue* outArrayQueue)
{
InitWithCapacity(typeSize, 0, outArrayQueue);
}
static ArrayQueue* Create(int typeSize)
{
return CreateWithCapacity(typeSize, 0);
}
_AArrayQueue_ AArrayQueue[1] =
{
Create,
Init,
CreateWithCapacity,
InitWithCapacity,
Release,
Push,
Pop,
RemoveAt,
};
有topIndex来标示当前队列元素的位置。push元素的时候,如果队列空位个数大于剩余容量就会触发一次元素移动,用来缓解触发容量的自增。