Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ linked list, removing element disconnects the rest of the list

I was trying to implement this simple linked list project for my homework. When I tried to implement the removeByKey function, I ran into the problem that it disconnects the rest of the list entirely when it finds the key to be removed.

Here’s the class:

class LancElem
{
private:
    int key;
    LancElem* next;
public:
    LancElem(){next = nullptr;}
    LancElem(int keyy, LancElem* nextt){key = keyy;next = nextt;}
    LancElem* getNext(){return next;}
    int getKey(){return key;}
    void setNext(LancElem* nextt){next = nextt; }
    void setKey(int keyy){key = keyy;}
};

The remove fucntion:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void removeByKey(LancElem& head, int key){
    LancElem* n = head.getNext();
    while(n->getNext()!=nullptr){
        if(n->getNext()->getKey()==key){
            n->setNext(n->getNext()->getNext());
            delete n->getNext();
            break;
        }
        n=n->getNext();
    }
}

When I try to remove the biggest element:

The original linked list: 4 1 9 8 2 7 3 6 3

Expected output: 4 1 8 2 7 3 6 3

The real output: 4 1 0

The problem is probably where I connect the current element to the next->next element but I can’t figure out why my implementation isn’t good.

>Solution :

Ask yourself:

What is n->next after the line n->setNext(n->getNext()->getNext()); ? What does the line delete n->getNext(); delete?

You don’t want to delete the just updated next but you want to delete the to be removed element:

        auto to_be_deleted = n->getNext(); 
        n->setNext(to_be_deleted->getNext());
        delete to_be_deleted;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading