반응형
List 구조에 대해서 Test 해볼수 있는 Basic 한 예제이다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NLEN 100
typedef struct _Fruit
{
char name[NLEN];
float score;
struct _Fruit* next;
}Fruit;
void print_all(Fruit* head)
{
Fruit* search = head;
printf("-------------------------------------\n");
printf("Head address = %x\n",(unsigned int)head);
while(search != NULL)
{
printf("%x\t%s\t%f\t%x\n",(unsigned int)search, search->name, search->score, (unsigned int)search->next);
search = search->next;
}
}
int main(void)
{
Fruit* head = NULL;
Fruit* temp = NULL;
Fruit* search = NULL;
Fruit* prev = NULL;
int count = 0;
/*First Node*/
Fruit* new_node = (Fruit*)malloc(sizeof(Fruit));
strcpy(new_node->name,"Apple");
new_node->score = 9.3f;
new_node->next = NULL;
if(head == NULL)
{
head = new_node;
}
print_all(head);
/*Second Node*/
new_node = (Fruit*)malloc(sizeof(Fruit));
strcpy(new_node->name, "Banana");
new_node->score = 8.4f;
new_node->next = NULL;
/*Add Front*/
temp = head;
head = new_node;
new_node->next = temp;
print_all(head);
/*Thrid Node*/
new_node = (Fruit*)malloc(sizeof(Fruit));
strcpy(new_node->name,"Orange");
new_node->score = 6.5f;
new_node->next = NULL;
/*Add back*/
search = head;
while(search->next !=NULL)
{
search = search->next;
}
search->next = new_node;
print_all(head);
/*Find and Delete an Item*/
search = head;
while(search!=NULL)
{
if(strcmp(search->name,"Apple")==0)break;
prev = search;
search = search->next;
count++;
}
if(search == NULL)
{
printf("Wrong name\n");
return;
}
if(prev == NULL)
{
head = search->next;
}
else
{
prev->next = search->next;
}
free(search);
print_all(head);
return 0;
}
해당 결과는 아래와 같습니다.
반응형
'Computer Language > Data Structure' 카테고리의 다른 글
[자료구조] 05. Queue List 구조 예제 (C언어) (0) | 2021.07.10 |
---|---|
[자료구조] 04. Queue 배열 구조 예제 (C언어) (0) | 2021.07.10 |
[자료구조] 03. Stack Flood Fill 예제 (C언어) (0) | 2021.07.10 |
[자료구조] 02. Stack 구조 Basic 예제 (C언어) (0) | 2021.07.09 |
[자료구조] 00. 자료 구조 들어가기 전, 배열구조 예제 (C언어) (0) | 2021.07.09 |
댓글