✨컴공주✨ [1052682] · MS 2021 (수정됨) · 쪽지

2023-01-18 23:05:12
조회수 1,938

컴공 일기224

게시글 주소: https://orbi.kr/00061423594

심심할 때 스스로 짜보고 고민해보는 싱글 링크드 리스트!


Remove 함수를 조금 더 쉽게 짜기 위해서 더미헤드를 도입해봤습니다 :-)

보편적인 기법이지용


곧 이것과 관련해서 블로그에 포스트를 할 생각입니다. 재미삼아 짜보는 거지만 곧 자료구조 공부이기도 하니까용


여하튼 코딩은 짱 재미있어용 :)



#include <stdio.h>

#include <stdlib.h>

#include <string.h>


typedef struct Node

{

    int Data;

    struct Node* next;

}Node;



Node* g_pHead = NULL;


void InitList()

{

    g_pHead = (Node*)malloc(sizeof(Node));

    g_pHead->next = NULL;

    g_pHead->Data = -1;

}


int Empty()

{

    if (g_pHead->next == NULL)

        return 1;

    else

        return 0;

}



void InsertAtHead(int pData)

{

    Node* pNode = (Node*)malloc(sizeof(Node));


    pNode->Data = pData;

    pNode->next = NULL;


    if (Empty())

    {

        g_pHead->next = pNode;

    }


    else {

        pNode->next = g_pHead->next;

        g_pHead->next = pNode;

    }



}


void InsertAtTail(int pData)

{

    Node* pNode = (Node*)malloc(sizeof(Node));

    pNode->Data = pData;

    pNode->next = NULL;



    Node* Cur = g_pHead->next;

    while (Cur->next != NULL)

    {

        Cur = Cur->next;

    }


    Cur->next = pNode;

}


Node* FindData(int pData)

{

    Node* cur = g_pHead->next;

    Node* prev = g_pHead;


    while (cur != NULL)

    {

        if (cur->Data == pData)

            return prev;


        else 

        { 

            cur = cur->next;

            prev = prev->next;

        }

    }


    return NULL;

}


int Remove(int pData)

{

    Node* pPrev = FindData(pData);

    if (pPrev != 0)

    {

        Node* pDelete = pPrev->next;

        pPrev->next = pDelete->next;


        printf("DeleteData():%d\n", pDelete->Data);


        free(pDelete);

        return 1;

    }

}



void PrintList()

{

    Node* Cur = g_pHead->next;


    while (Cur != NULL)

    {

        printf("Current-Node:[%p], Next-Node:[%p], Data:%d\n", Cur, Cur->next, Cur->Data);

        Cur = Cur->next;

    }

}


int main()

{


    //테스트를 위한 코드 

    InitList();


    InsertAtHead(4);

    InsertAtHead(3);

    InsertAtHead(2);

    InsertAtHead(1);


    InsertAtTail(5);

    InsertAtTail(6);


    Remove(1);

    Remove(3);

    Remove(4);



    PrintList();

}




컴파일 결과 : 


DeleteData():1

DeleteData():3

DeleteData():4

Current-Node:[000002CB614CE2E0], Next-Node:[000002CB614CE290], Data:2

Current-Node:[000002CB614CE290], Next-Node:[000002CB614CE330], Data:5

Current-Node:[000002CB614CE330], Next-Node:[0000000000000000], Data:6

0 XDK (+0)

  1. 유익한 글을 읽었다면 작성자에게 XDK를 선물하세요.