Создан связанный список, но как удалить «все» узлы в c ++ - PullRequest
0 голосов
/ 07 октября 2018

Я написал следующий код для создания связанного списка.Итак, я хотел знать, как удалить все узлы связанного списка.И я также хотел знать, как правильно я создал узлы и вставил в них элементы .

struct node
{
    int val;
    node *next;
};
int main()
{
    node *head, *temp;
    cout << "enter no of elements" << endl;
    int n;
    cin >> n;

    //=============Creating Nodes And Inserting Elements===========//
    for(int i = 0; i < n; i++)
    {
        cout << "enter the element in " << i << "th node" << endl;
        if(i == 0)
        {
            temp = new node(); 
            cin >> temp->val; 
            head = temp;
        }
        else
        {
            temp->next=new node();
            temp=temp->next;
            cin >> temp->val;
        }
    }
    temp->next=NULL;

    //===================Deleting all the nodes=================//


    return 0;
}

Ответы [ 4 ]

0 голосов
/ 07 октября 2018

Самый очевидный вопрос: почему вы создаете свой собственный список вместо того, чтобы использовать что-то из STL, например std::list?То, как вы пишете код, больше похоже на C, чем на C ++.Методы добавления, удаления и т. Д. Узлов должны быть функциями-членами структуры узла.Например:

struct node
{
    int val;
    node *next;

    explicit node(int val = 0) : val{val}, next{nullptr} {}

    void add_node(node *nodep) {
        node *tail = this;
        while (tail->next != nullptr)
            tail = tail->next;
        tail->next = nodep;
    }

    ~node() {
        delete next;
    }
};

Но использование контейнера из STL действительно лучше.

0 голосов
/ 07 октября 2018

Вы можете создать связанный список несколькими способами, я покажу вам их путь:

Структура:

struct linkedList {
    int data;         // store data
    linkedList *next; // store a pointer to the next node
} *head; // "head" is a pointer points to the first node

Следующая функция представляет собой простой способ созданияновый узел:

void InsertNode(int data){
    linkedList *node = new linkedList;
    node->data = data;
    node->next = head;
    head = node;
}

И когда вы хотите удалить все узлы, которые в связанном списке:

void deleteAllNodes(){
    linkedList *temp = head, *next;
    while(temp != NULL){
        next = temp->next;
        delete temp;
        temp = next;
    }
    delete head;
    head = NULL;
}

Если есть что-то неясное, комментарий.

0 голосов
/ 07 октября 2018

используйте деструктор

struct node
{
    ~node()
    {
        if (NULL != next)
        {
            delete next;
        }
    }

    int val;
    node *next = NULL; //initialize with NULL
};

теперь из основного узла удаления головы

int main()
{
    ...
    delete head;
    ...
}
0 голосов
/ 07 октября 2018

Вы delete все узлы, пройдя по списку:

node *temptemp;      // tempory variable to store
                     // the next list nodes address
for (temp = head;    // begin at the head of the list
     temp;           // as long as temp != NULL
     temp = temptemp // the temp->next we stored in the loops body
) {
    temptemp = temp->next;  // remember temp->next cause
    delete temp;            // next is gone now.
}
...