연결리스트(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
'자료구조' 카테고리의 다른 글
[자료구조 4장] - 연결리스트(4) (2) | 2024.02.18 |
---|---|
[자료구조 4장] - 연결리스트(2) (0) | 2024.01.30 |
[자료구조 4장] - 연결리스트(1) (0) | 2024.01.20 |
[자료구조 3장] - 배열과 구조체(3) (1) | 2024.01.14 |
[자료구조 3장] - 배열과 구조체(2) (2) | 2024.01.07 |
jyppro님의
글이 좋았다면 응원을 보내주세요!
이 글이 도움이 됐다면, 응원 댓글을 써보세요. 블로거에게 지급되는 응원금은 새로운 창작의 큰 힘이 됩니다.
응원 댓글은 만 14세 이상 카카오계정 이용자라면 누구나 편하게 작성, 결제할 수 있습니다.
글 본문, 댓글 목록 등을 통해 응원한 팬과 응원 댓글, 응원금을 강조해 보여줍니다.
응원금은 앱에서는 인앱결제, 웹에서는 카카오페이 및 신용카드로 결제할 수 있습니다.