code

C: 링크된 목록에서 노드를 해제하는 방법은 무엇입니까?

starcafe 2023. 6. 27. 22:25
반응형

C: 링크된 목록에서 노드를 해제하는 방법은 무엇입니까?

다른 기능에 할당된 노드를 해제하려면 어떻게 해야 합니까?

struct node {
    int data;
    struct node* next;
};

struct node* buildList()
{
    struct node* head = NULL;
    struct node* second = NULL;
    struct node* third = NULL;

    head = malloc(sizeof(struct node));
    second = malloc(sizeof(struct node));
    third = malloc(sizeof(struct node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    return head;
}  

메인()에서 buildList 함수를 호출합니다.

int main()
{
    struct node* h = buildList();
    printf("The second element is %d\n", h->next->data);
    return 0;
}  

저는 머리, 두 번째, 세 번째 변수를 자유롭게 하고 싶습니다.
감사해요.

업데이트:

int main()
{
    struct node* h = buildList();
    printf("The element is %d\n", h->next->data);  //prints 2
    //free(h->next->next);
    //free(h->next);
    free(h);

   // struct node* h1 = buildList();
    printf("The element is %d\n", h->next->data);  //print 2 ?? why?
    return 0;
}

둘 다 프린트 2.free(h) remove h를 호출하면 안 됩니다.그렇다면 h->next->next->데이터를 사용할 수 있는 이유는 무엇입니까, 만약 그가 무료라면.물론 '두 번째' 노드는 해제되지 않습니다.그러나 머리가 제거되었기 때문에 다음 요소를 참조할 수 있어야 합니다.여기서 뭐가 잘못됐습니까?

목록을 해제하는 반복 기능:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

기능이 수행하는 작업은 다음과 같습니다.

  1. 확인해 보다headnull입니다. yes인 경우 목록이 비어 있고 그냥 돌아갑니다.

  2. 저장head순식간에tmp변수 및 만들기head목록의 다음 노드를 가리킵니다(이 작업은 에서 수행됨).head = head->next

  3. 이제 안전하게 할 수 있습니다.free(tmp)변수 및head목록의 나머지 부분만 가리키면 1단계로 돌아갑니다.

목록 위에서 반복하기만 하면 됩니다.

struct node *n = head;
while(n){
   struct node *n1 = n;
   n = n->next;
   free(n1);
}

하나의 기능이 그 일을 할 수 있습니다.

void free_list(node *pHead)
{
    node *pNode = pHead, *pNext;

    while (NULL != pNode)
    {
        pNext = pNode->next;
        free(pNode);
        pNode = pNext;
    }

}
struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

항상 다음과 같이 재귀적으로 수행할 수 있습니다.

void freeList(struct node* currentNode)
{
    if(currentNode->next) freeList(currentNode->next);
    free(currentNode);
}

언급URL : https://stackoverflow.com/questions/6417158/c-how-to-free-nodes-in-the-linked-list

반응형