티스토리 뷰

C/자료구조

배열을 이용한 리스트

NationCore 2019. 3. 13. 16:23

#include <stdio.h>

#include <stdlib.h>


#define MAX_LIST_SIZE 100


typedef struct {

int list[MAX_LIST_SIZE];

int length;

} Array_list;


void error(char *message)

{

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

exit(1);

}


void init(Array_list *list)

{

list->length = 0;

}


int is_empty(Array_list *list)

{

return list->length == 0;

}


int is_full(Array_list *list)

{

return list->length == MAX_LIST_SIZE;

}


void display(Array_list *list)

{

for (int i = 0; i < list->length; i++)

{

printf("[%d]: %d\n",i+1,list->list[i]);

}

}


void add(Array_list *list, int pos, int data)

{

if (!is_full(list) && (pos >= 0) && (pos <= list->length))

{

int i;

for (i = (list->length - 1); i >= pos; i--)

list->list[i + 1] = list->list[i];

list->list[pos] = data;

list->length++;

}

}


int delete(Array_list *list, int pos)

{

int tmposdata;

if (pos < 0 || pos >= list->length)

error("위치오류");

tmposdata = list->list[pos];

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

list->list[i] = list->list[i + 1];

list->length--;

return tmposdata;

}


void main(void)

{

Array_list static_list;

Array_list *dynamic_list;


init(&static_list);

add(&static_list, 0, 20);

add(&static_list, 0, 30);

add(&static_list, 0, 40);

display(&static_list);



dynamic_list = (Array_list *)malloc(sizeof(Array_list));

init(dynamic_list);

add(dynamic_list, 0, 20);

add(dynamic_list, 0, 40);

add(dynamic_list, 0, 30);

display(dynamic_list);

free(dynamic_list);

}



결과 :



'C > 자료구조' 카테고리의 다른 글

이중 연결 리스트  (0) 2019.03.13
원형 리스트  (0) 2019.03.13
자체 참조 구조체를 이용한 동적 리스트  (0) 2019.03.13
자체 참조 구조체  (0) 2019.03.11
작동시간 코드  (0) 2019.03.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/07   »
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
글 보관함