[자료구조] 배열리스트의 특징과 원소 추가 제거 방법

2021. 4. 27. 00:52
728x90

- 배열리스트(ArrayList)

논리적 (저장)순서와 물리적 저장 순서가 동일하다

 

원소의 위치 인덱스는 0부터 시작한다 (C배열에서와 동일)

 

배열리스트의 단점

원소의 개수가 10만개인 배열리스트에서 원소의 추가/제거가 빈번하게 발생한다면?

중간에 추가 제거가 일어날때 해당 데이터와 관계없는 데이터들의 이동이 필요하다


배열리스트의 원소 추가

추가전 시작 지점과 방향, 어디까지 의 3가지 점을 주의해야함

1의 위치에 5를 삽입하기위해

가장 뒤에 있는값을 하나씩 옮긴 후 새로운 데이터를 삽입한다

 

추가가능한 위치인지 확인 필요

newElementCount 개수 만큼 값을 추가로 저장할 수 있음

int addALElement(ArrayList* pList , int position, ArrayListNode element){
	int ret = FALSE;
    int i = 0;
    
    if(pList != NULL){
      if(isArrayListFull(pList) != TRUE) {
        if(position >= 0 && position <= pList -> currentElementCount){
           for(i = pList -> currentElementCount-1; i >=position; i--) {
               pList -> pElement[i+1] = pList -> pElement[i];
              }
               pList -> currentElementCount++;
               
               ret = TRUE;
            } else {
               printf("오류, 위치 인덱스 -[%d] 범위 초과, addALElement()\n",position);
            }
         } else{
            printf("오류, 리스트 용량 초과 [%d]/[%d] \n",position, pList ->maxElementCount);
         }
     }
     
     return ret;
 }

배열리스트의 원소 제거

제거 후 시작 ,방향, 어디까지의 3가지를 생각해야한다

가장 앞에 있는 0번째 데이터를 제거하기 위해

값을 제거하고 나머지 데이터들을 한칸씩 앞으로 이동한다

 

int removeALElement(ArrayList* pList, int position){
 int i = 0;
 
 if(pList != NULL) {
  if(position >= 0 && position < pList -> currentElementCount){
    for (i = position ; i < pList -> currentElementCount-1; i++){
    	pList -> pElement[i] = pList->pElement[i+1];
    }
    pList -> currentElementCount--;
    ret = TRUE;
   }
   else {
     printf("오류, 위치인덱스 범위 초과, removeALElement()\n", position);
   }
  }
  return ret;
}

 

반응형

BELATED ARTICLES

more