반응형
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);
}
}
기능이 수행하는 작업은 다음과 같습니다.
확인해 보다
head
null입니다. yes인 경우 목록이 비어 있고 그냥 돌아갑니다.저장
head
순식간에tmp
변수 및 만들기head
목록의 다음 노드를 가리킵니다(이 작업은 에서 수행됨).head = head->next
- 이제 안전하게 할 수 있습니다.
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
반응형
'code' 카테고리의 다른 글
UIS 검색 디스플레이 컨트롤러/UIS 검색 막대를 사용하여 NSFetched Results Controller(핵심 데이터)를 필터링하는 방법 (0) | 2023.06.27 |
---|---|
과거에 임의의 커밋 두 개 사이에 커밋을 삽입하는 방법은 무엇입니까? (0) | 2023.06.27 |
빈 data.frame을 생성합니다. (0) | 2023.06.27 |
Springboot 스프링 액추에이터 상태 끝점에서 Mongo 상태 표시기를 비활성화할 수 있습니까? (0) | 2023.06.27 |
코드에서 장치의 IP 주소를 가져오는 방법은 무엇입니까? (0) | 2023.06.27 |