Question

I'm trying to get my remove function to work for a doubly linked list. I feel like my code is correct, but it keeps breaking. I believe it has something to do when I delete the node but I'm not sure the compiler keeps taking me to a throw.cpp? So I'm not quite sure whats wrong. Here is my code:

  ItemType remove(int index) 
  {
    ItemType name;
    Node* temp;
    Node* current;
    int pos = 0;
    int endpos = size - 1;

    if (index >= 0 && index <= size)
    {
        if (index == 0)
        {
            temp = head;
            delete head;
            head = temp->next;
            size--;
            name = temp->info;
            return name;
        }
        else if (index == size - 1)
        {
            temp = tail;
            delete tail;
            tail = temp->prev;
            size--;
            name = temp->info;
            return name;
        }
        else if (index <= size/2)
        {
            current = head;
            while (pos != index)
            {
                current = current->next;
                pos++;
            }
        }
        else if (index > size/2)
        {           
            current = tail;
            while (endpos != index)
            {
                current = current->prev;
                endpos--;
            }
        }
    }

    temp = current;
    current->prev->next = current->next;
    current->next->prev = current->prev;
    delete current;
    size--;
    name = temp->info;
    return name;


  }

if anyone can see what might be the problem that would be sweet.

Was it helpful?

Solution

What is the error?

Some suggestion, when deleting the head and tail, set the new head/tail pointer first before deleting the old one. So the code

 temp = head;
 delete head;
 head = temp->next;

should be changed to

 temp = head;
 head = temp->next;
 delete temp;

Do the same for the tail. This is because when you call delete head, the temp which is pointing the same location with head now have garbage values, so you can't just use temp->next in the subsequent commands.

Also when calling name = temp->info, make sure it is before the variable is deleted.

OTHER TIPS

Here are few corrections

instead of this

if (index >= 0 && index <= size)

use

 if (index >= 0 && index < size)

You are deleting the node before updating the pointer thats why this will crash. So first you need to update head pointer then delete temp. Like this

temp = head;
head = head->next;
delete temp;

same applies while deleting the tail pointer also

temp = tail;
tail = tail->next;
delete temp;

Here delete temp not current

temp = current;
current->prev->next = current->next;
current->next->prev = current->prev;
delete temp;

and use

name = current->info;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top