이번에는 linked list 말고, array list를 구현해 보자.
#ifndef _ARRAYLIST_
#define _ARRAYLIST_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct ArrayListNodeType
{
int data;
} ArrayListNode;
typedef struct ArrayListType
{
int maxElementCount; // 최대 원소 개수
int currentElementCount; // 현재 원소의 개수
ArrayListNode *pElement; // 원소 저장을 위한 1차원 배열
} ArrayList;
ArrayList* createArrayList(int maxElementCount);
void deleteArrayList(ArrayList* pList);
int isArrayListFull(ArrayList* pList);
int addALElement(ArrayList* pList, int position, ArrayListNode element);
int removeALElement(ArrayList* pList, int position);
ArrayListNode* getALElement(ArrayList* pList, int position);
void displayArrayList(ArrayList* pList);
void clearArrayList(ArrayList* pList);
int getArrayListLength(ArrayList* pList);
#endif
#ifndef _COMMON_LIST_DEF_
#define _COMMON_LIST_DEF_
#define TRUE 1
#define FALSE 0
#endif
array list에서 쓰이는 구조체는 2개가 있다. 최대 원소 개수와 현재 원소 개수, 배열의 포인터(ArrayList 배열)를 저장하는 ArrayList 구조체가 있고, 원소 1개를 나타내는 ArrayList구조체가 있다. 배열의 포인터인 pElement는 배열의 제일 첫번째 원소(0번째 원소)의 주소를 가진다.
즉, ArrayList의 pElement가 ArrayListNode를 가리킬 수 있게 한다.

ArrayList* createArrayList(int maxElementCount)
{
ArrayList* pList;
if (maxElementCount < 0)
{
printf("maxElementCount minus\\n");
}
pList = (ArrayList *)malloc(sizeof(ArrayList));
if (!pList)
{
printf("pList malloc failure\\n");
return (NULL);
}
pList->maxElementCount = maxElementCount;
pList->currentElementCount = 0;
pList->pElement = (ArrayListNode*)malloc(sizeof(ArrayListNode) * maxElementCount);
if (!(pList->pElement))
{
printf("pElement malloc failure\\n");
free(pList);
return (NULL);
}
memset(pList->pElement, 0, sizeof(ArrayListNode) * maxElementCount);
return (pList);
}
함수 기능 : maxElementCount만큼의 원소가 있는 배열리스트 할당하고 이 주소값을 반환하는 함수.
<aside> 💡 함수 구현 방법
</aside>
(1) maxElement < 0일 때 예외처리하기
(2) pList에 ArrayList만큼 메모리 동적할당 후 동적할당 실패 시 예외처리
(3) pList의 멤버변수인 maxElementCount에 maxElementCount를, currentElementCount = 0으로 값 넣기.
(4) pList의 pElement에 maxElementCount만큼의 노드를 할당하고, 할당 실패 시 pList free하고 예외처리
(5) memset으로 할당된 노드들에 모두 0값 넣어주기
int addALElement(ArrayList* pList, int position, ArrayListNode element)
{
if (isArrayListFull(pList) == TRUE || pList == NULL || position > pList->currentElementCount || position < 0)
{
return (FALSE);
}
else
{
for(int i = pList->currentElementCount; i > position; i--)
{
pList->pElement[i] = pList->pElement[i - 1];//뒤로 미루기
}
pList->pElement[position] = element;
pList->currentElementCount++;
return (TRUE);
}
}