본문 바로가기
혼자 공부하는 것들/자료구조(c언어)

C)Link List 구현

by applepick 2020. 7. 17.
반응형

 

C언어로 직접 구현해본 Link List입니다. 위에 링크는 소스가 들어간 Git주소입니다. 많은 피드백 해주시면 감사합니다.

일단 제가 구현한 소스는 학생이름,학번,점수 이렇게 꾸려보았습니다. 각 소스에 주석을 달아놓겠습니다.

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {  
    char name[10];
    int hakbun;
    int score;
    struct student *next;      ///다음학생을 가르키는 포인터
};

struct student *head = NULL;  ///구조체의 첫 부분을 null로 초기화시켜준다.
int list_size = 0;  

void add_head(const char *name, int hakbun, int score)  ///노드의 해드를 만들어주는 로직.
{
    struct student *node;

    node = malloc( sizeof(struct student) );   ///생성 된 노드를 효율적으로 사용하기위해
    strcpy(node->name, name);                 ///사용하는 만큼만 메모리를 할당시켜준다.
    node->hakbun = hakbun;
    node->score = score;

    node->next = head;
    head = node;
    list_size++;
}


void add_tail(const char *name, int hakbun, int score) ///생성된 노드의 마지막부분에 할당시켜주는 로직.
{
    struct student *node;
    node = malloc( sizeof(struct student) );
    strcpy(node->name, name);
    node->hakbun = hakbun;
    node->score = score;

    if (head == NULL)
    {
        node->next = NULL;
        head = node;

    }
    else
    {
        struct student *p = head;
        while(p->next != NULL)
            p = p->next;

        // p는 마지막 노드
        p->next = node;
        node->next = NULL;
    }
    list_size++;
}



void print_list( )              ///구조체를 출력해주는 함수.
{
    struct student *p;

    p = head;
    while (p != NULL)
    {
        printf("--> %s ", p->name);
        p = p->next;
    }
    printf("\n");
}

int add( int index, const char *name,int hakbun, int score )   ///자기가 원하는 번호에 노드를 추가해주는 로직.
{
   struct student *node;
   struct student *newNode,*temp;

    newNode = malloc( sizeof(struct student) );    ///기존 노드와 햇갈리지않게 새로운 노드를 할당.
    strcpy(newNode->name, name);
    newNode->hakbun = hakbun;
    newNode->score = score;

    node = malloc( sizeof(struct student) );
    strcpy(node->name, name);
    node->hakbun = hakbun;
    node->score = score;

    if ( index<0 && index>list_size )      /// 잘못된 index 처리
        return 0;

    if (index == 0)        /// index=0 일 때, 맨 앞에 새로운 노드 추가
    {
        node->next = head;
        head = node;
        list_size++;
        return 1;
    }

    struct student *p = head;      /// 포인터 p를 (index-1)번 노드까지 이동

    for(int i=0;i<index-1;i++)
    {
        p = p->next;
    }
    temp = p->next;
    p->next= newNode;
    newNode->next=temp;



    /// p 뒤에 새로운 노드 추가
        while(p->next != NULL)
            p = p->next;

        p->next = NULL;

    list_size++;
    return 1;
}

struct student *get_tail()  ///마지막 구조체의 위치를 얻는 로직.
{
    struct student *p;

    if(head == NULL)
        return NULL;

    p= head;
    while(p->next!=NULL)
            p = p->next;
    return p;
}

struct student *get(int index) 
{ 
    ///잘못된 index 처리
    if(index < 0  ||  index > list_size)
        return NULL;

    ///포인터 p를 index번 노드까지 이동
    struct student *p = head;

    for(int i=0; i<index;i++)
        p = p->next;

    return p;
}

int del(int index)  ///원하는 위치에서 구조체를 삭제해주는 로직.
{
    struct student *delNode;

    if(index < 0 && index < list_size)
        return 0;

    ///index=0일때, 매앞 노드 삭제
    if(index == 0)
    {
        delNode = head;
        head = delNode->next;
        free(delNode);
        list_size--;
        return 1;
    }
    struct student *p = head;
    struct student *q = head;

    for(int i=0;i<index-1;i++)
        p= p->next;

    q= p->next;
    p->next = q->next;
    q->next = p;

    free(q);
    list_size--;
    return 1;
}

int del_head() ///제귀를 사용하여 해드부분 구조체를 삭제
{
    return del(0);
}

int del_tail()  ///제귀를 사용하여 마지막부분 구조체를 삭제
{
    return del(list_size-1);
}



int main()
{
    add_head("James", 2012330, 80); print_list();
    add_head("Tom", 2013522, 95); print_list();
    add_head("Kate", 2012621, 99); print_list();

    add_tail("Nick", 2018052, 83); print_list();
    add_tail("Alice", 2019114, 77); print_list();
    add(3,"David", 2013581, 59); print_list();

    struct student *p;
    p = get(3);
    if(p!=NULL)
        printf("%s %d %d \n",p->name, p->hakbun, p->score);

    del_head(); print_list();
    del(3); print_list();
    del_tail(); print_list();


}

이처럼 코드를 작성했는데 자료구조나 프로그래밍 수업을 듣는 학생이라면 도움이 되었으면좋겠습니다.

반응형

댓글