본문 바로가기
자료구조

[자료구조 4장] - 연결리스트(3)

by jyppro 2024. 2. 8.

연결리스트(3)

 

응용 프로그램

 

동물연결리스트 예제

동물농장에 있는 5가지 동물의 종류(문자배열)와 동물의 수를 연결리스트로 구축하여 출력하는 프로그램을 작성하자. 우선 dog 10 하나의 데이터 항목 1개의 노드가 초기에 주어져 있고 4가지 동물의 종류와 동물의 수를 받아 차례로 연결하는 프로그램이다.

typedef struct fnode *fpointer;
struct node {
    char animal[10];
    int item;
    fpointer next;
};


void main()
{
    fpointer head=NULL, ptr, another, before;
    int k, how_many=0;
    
    head = (fpointer) malloc(sizeof(struct fnode));
    strcpy(head->animai, "dog");
    head->item = 10;
    head->next = NULL;
    
    for(k = 0; k < 4; k++){
        another = (fpointer) malloc(sizeof(struct fnode));
        printf("Enter the sort of animal and its number: ");
        scanf("%s %d", (another->animai), &(another->item));
        ptr = head;
        while(ptr != NULL) {
            before = ptr;
            ptr = ptr -> next;
        }
        before -> next = another;
        another -> next = NULL;
    }
    printf("========================\n");
    ptr = head;
    while(ptr != NULL) {
        printf("%s: %d\n", ptr->animal, ptr->item);
        how_many += ptr->item;
        ptr = ptr -> next;
    }
    printf("Total number of items: %d\n", how_many);
}

 

실행결과

Enter the sort of animal and its number : cat 7
Enter the sort of animal and its number : rabbit 12
Enter the sort of animal and its number : chicken 11
Enter the sort of animal and its number : monkey 3
========================
dog  :  10
cat  :  7
rabbit  :  12
chicken  :  11
monkey  :  3
Total number of items: 43