본문 바로가기

Programming/DS SorceCode

ArrayList.h : 배열을 이용한 리스트 클래스 구현

#pragma once

#ifndef ___ArrayList

#define ___ArrayList

//ArrayList.h : 배열을 이용한 리스트 클래스 구현


#include <cstdio>

#include <cstdlib>

#define MAX_LIST_SIZE 100

//오류 처리 함수

inline void error(const char *message) {

printf("%s\n", message);

exit(1);

}


class ArrayList {

int data[MAX_LIST_SIZE]; //실제로 항목 값들이 들어감

int length; //현재 리스트 내의 항목들의 개수

public:

ArrayList(void) { length = 0; } //생성자 ==> length을 초기화


//삽입 연산 : 리스트의 pos번째에 항목 e추가

void insert(int pos, int e);

//삭제 연산 : pos번쨰에 항목을 리스트에서 제거

void remove(int pos);


int getEntry(int pos) { return data[pos]; } //pos번째 항목을 반환

bool isEmpty() { return length == 0; } //공백 상태 검사

bool isFull() { return length == MAX_LIST_SIZE; } //포화 상태 검사

bool find(int item) { //item 항목이 있는지 검사

for (int i = 0; i < length; i++)

if (data[i] == item) return true;

return false;

}

void replace(int pos, int e) { //pos위치의 요소 변경

data[pos] = e;

}

int size() { return length; } //리스트의 길이 반환

void display() { //화면에 보기 좋게 출력

printf("[배열로구현한리스트 전체 항목 수 = %2d] : ", size());

for (int i = 0; i < size(); i++)

printf("[%2d] ", data[i]);

printf("\n");

}

void clear() { length = 0; } //모든 요소 제거

};

//List에 pos번째에 요소 e추가

void ArrayList::insert(int pos, int e) {

if (!isFull() && pos >= 0 && pos <= length) { //리스트의 맨 끝에도 자료를 추가할 수 있어야 함

for (int i = length; i > pos; i--)

data[i] = data[i - 1]; //뒤로 한 칸씩 밀고

data[pos] = e; //pos에 e를 복사하고

length++; //리스트 항목의 개수 증가

}

else error("포화상태 오류 또는 삽입 위치 오류");

}

//리스트의 pos번째 요소 삭제

void ArrayList::remove(int pos) {

if (!isEmpty() && 0 <= pos && pos < length) { //유효한 위치 검사

for (int i = pos + 1; i < length; i++)

data[i - 1] = data[i]; //앞으로 당기고

length--; //개수 감소

}

else error("공백상태 오류 또는 삭제 위치 오류");

}


#endif // !___ArrayList