简体   繁体   中英

Doubly linked list delete even numbers in C++

I'm trying to delete all even numbers from a doubly linked list.

I've considered the cases as:

  1. empty list
  2. even number at beginning,
  3. even number at the end
  4. even number in the middle of the list
  5. even number not in the list

My code below won't work properly:

void DoublyList::deleteEvens()
{

    if (first == NULL) {
        cerr << "Empty List" << endl;
    }


    else {
        Node *current = first;
        bool found = false;
        while (current != NULL && (!found)) {
            Node *tCurrent = current;
            if (current->getNextLink() == NULL) {
                if (current->getData() % 2 == 0) {
                    first = NULL;
                    last = NULL;
                    delete current;
                    current = NULL;
                    count = 0;
                }
                else {
                    cerr << "Not in the list" << endl;
                    found = true;
                }
            }

            else if (current == first && current->getData() % 2 == 0) {
                first = first -> getNextLink();
                first->setPreviousLink(NULL);
                current = current->getNextLink();
                delete tCurrent;
                tCurrent = NULL;
                -- count;
            }
            else if (current == last && current->getData() % 2 == 0) {
                last = last->getPreviousLink();
                last->setNextLink(NULL);
                delete current;
                current = NULL;
                -- count;
            }

            else if (current->getData() % 2 == 0) {
                current->getPreviousLink()->setNextLink(current->getNextLink());
                current->getNextLink()->setPreviousLink(current->getPreviousLink());
                current = current->getNextLink();
                delete tCurrent;
                tCurrent = NULL;
            }
            else {
                current = current->getNextLink();
            }
        }
    }
}

The issue seems to be your first case: current->getNextLink() == NULL will evaluate to true for that last item in the list. So, when you process the last item, you effectively delete the entire list.

I assume this is meant to detect the first item in the list, change it to:

if (current->getNextLink() == NULL && current->getPreviousLink() == NULL)

or, alternatively, move it outside the loop and just use the first variable.

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