본문 바로가기
Computer Language/Data Structure

[자료구조] 01. List 구조 Baisc 예제 (C언어)

by 방구석 임베디드 2021. 7. 9.
반응형

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;
}

해당 결과는 아래와 같습니다.

반응형

댓글