【问题标题】:Deleting A Node From A Singly Linked List -- Using MALLOC/FREE从单链表中删除节点 -- 使用 MALLOC/FREE
【发布时间】:2013-04-02 23:39:36
【问题描述】:

我正在编写从单链表中删除节点的常见方法,但我不确定我删除它们的方式(通过使用 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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      希望这可以帮助,使用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;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-04
        • 2021-02-21
        • 1970-01-01
        • 2018-09-04
        • 2021-03-10
        相关资源
        最近更新 更多