从单链接列表中删除节点 - 使用MALLOC / FREE

问题描述 投票:0回答:2

我正在编写从单链表中删除节点的常用方法,但我不确定我删除它们的方式(使用FREE())是否正确。我想真正删除节点并释放内存。我提供了Node的strut定义以及Node结构的创建方式。

我在Java中理解,任何时候都没有指向数据,它会自动清理。我想C,我必须免费使用,但我是否正确使用它?例如下面,当我'免费'当前,我能够在之后做出其他东西吗?做这个的最好方式是什么?

谢谢,我希望我的问题很明确!

typedef struct Node {
    int data;
    struct Node *next;
} Node;

struct Node* newNode(int value) {
    struct Node* node = (Node *)malloc(sizeof(struct Node));
    if (node == NULL) {
        // malloc fails. deal with it.
    } else {
        node->data = value;
        node->next = NULL;
    }
    return node;
}

void delete(int value, struct node *head) {
    struct Node* current = head;
    struct Node* previous = NULL;

    while (current != NULL) {
        if (current->data == value) {
            if (previous == NULL) {
                current = current->next;
                free(head);
            } else {
                previous->next = current->next;
                free(current);
                current = previous->next;
            }
        } else {
            previous = current;
            current = current->next;
        }
    }    
}
c data-structures linked-list malloc
2个回答
1
投票

这是对的。当您使用free并提供指针时,指针当前指向的数据将在内存中释放。指针本身存储在别处,可用于指向'释放'后的不同数据。删除非头节点(previous->next = current->nextcurrent = previous->next)时,在正确的上一个节点和下一个节点之间创建链接是正确的。

我建议你的代码补充一点是,在释放head之后你应该将头指针重新分配给新的头部删除,在这种情况下是最新的。


0
投票

希望这可以帮助,使用free()命令

struct Node
{
     int data;
     struct Node *next;
}
Node* Delete(Node *head, int position)
{
  Node *temp1 = head;
  if(position==0){
      head = temp1->next;
      free(temp1);
      return head;
  }
  Node *temp2;
  while(position>1){
      temp1 = temp1->next;
      position--;
  }      
  temp2= temp1->next;
  temp1->next = temp2->next;
  free(temp2);
  return head;
}
© www.soinside.com 2019 - 2024. All rights reserved.