简体   繁体   中英

Linked List clear list function

I am currently working on a project, I have a circular doubly linked list which includes 2 integers as quantity and price , and 1 string as itemName . Here is my struct for node:

struct node {
        int quantity, price;
        string itemName;
        node * next;
        node * prev;
        node (int x = 0, int y = 0, string str = "", node * p = NULL, node * r = NULL): quantity(x), price(y), itemName(str), next(p), prev(r){}
    };

I am currently doing well, I did my addSorted function, print list function etc, and they work great. I have a problem about my clearList function. As I do my "new node" assignment in my addItem function, I can't delete nodes in my clearList function. Here is my clearList function:

void clear(node * head){
        if (head == NULL) {
            cout << "List is empty." << endl;
        }
        else {
            node * ptr = head->next;
            while(ptr != head)
            {
                ptr = head;
                head = head->next;
                delete ptr;
            }
        }
    }

I am having an error like this:

main(21281,0x100098600) malloc: *** error for object 0x103033080: pointer being freed was not allocated main(21281,0x100098600) malloc: *** set a breakpoint in malloc_error_break to debug

What is the problem, and how can I delete the nodes that I created in another function? How can I solve this problem? Thank you.

Think about your logic here

       node * ptr = head->next;
        while(ptr != head)
        {
            ptr = head;
            head = head->next;
            delete ptr;
        }

while (ptr != head) implies that in the while loop ptr does equal head but the very next line says ptr = head; A sure sign that you were confused when writing this code.

Another issue is that when all the nodes have been deleted you want to end up with head equal to NULL but your code doesn't do that.

Here's my effort

if (head == NULL) {
    cout << "List is empty." << endl;
}
else {
    node* n = head;
    do
    {
        node* next = n->next;
        delete n;
        n = next;
    }
    while (n != head);
    head = NULL;
}

Completely untested, use with caution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM