链接列表添加和删除整个列表

时间:2018-06-05 15:32:00

标签: linked-list

我正在尝试实现链接列表以保存从第一个输入到最后一个输入,我正确地存储和打印我的数据,但我不确定如何正确删除整个列表。我的嵌入式代码在X次交互添加,打印,删除后重新启动(当它发生时我的头指针地址增加,直到我的程序崩溃。

有人可以看一下我的删除(DeleteAll)功能

enter image description here

    #include "Linked_List.h"
#include <string.h>

// Construction
Linked_List::Linked_List()
{
    Node * Current_Nodes = NULL;
    Node * Head_Nodes = NULL;
    Node * Temporal_Nodes = NULL;
}

// Destruction
Linked_List::~Linked_List()
{
    DeleteAll();
}
// printing
void Linked_List::SendLinked_List()
{       
    if (Current_Nodes != NULL)
    {
        Current_Nodes = Current_Nodes->p_next;          
        // Populate the event message
        class ReportSensorEvent msg;

        UART_TX(Current_Nodes->key_id);     //printing my values using UART 
        UART_TX(Current_Nodes->data_user);  //printing my values using UART 
    }
}
//Adds item
void Linked_List::AddLinked_List(uint16_t key_id, uint8_t  data_user)
{
    Node * p_Node = new Node;

    memset(p_Node, 0, sizeof(Node));

    p_Node->key_id = key_id;        
    p_Node->data_user = data_user;
    p_Node->p_next = Current_Nodes;

    Current_Nodes = p_Node;
    Head_Nodes = p_Node;    //keep record for the last added node
}

// Deletes all
void Linked_List::DeleteAll()
{
    Current_Nodes =  Head_Nodes->p_next;    //last position added

    while (Current_Nodes != NULL)
    {
        Temporal_Nodes = Current_Nodes->p_next;         
        delete Current_Nodes;   

        Current_Nodes = NULL;
        Current_Nodes = Temporal_Nodes;
    }       
    if (Current_Nodes == NULL )
    {
        delete Head_Nodes;                  //if Head_Node is not deleted my node pointer will increase, after each add, print, delete iteration
        delete Temporal_Nodes;
        Head_Nodes = NULL;
        Temporal_Nodes = NULL;
    }   
}

此致

1 个答案:

答案 0 :(得分:0)

delete Temporal_Nodes;是双倍的delete,不允许。 (无论如何,为什么Temporal_Nodes不是局部变量?)