Please help - Linked List

Hi - I am desperately trying to finish my project and I cannot get the "insert" function to work properly. Basically, the function is going to receive a string dataVal and an index where the code needs to "insert" this item into the linked list. Below is my code - it doesn't work and i'm going nuts. Any help would be so very appreciated!

Thanks


void List::insert( ElementType dataVal, int index )

{
Node *newpointer = new Node();

if (index < 0 || index > size)
{
cout << "Error: Illegal insert position" << endl;
return;
}

Node * predPtr = NULL;

if ( index == 0)
{
return;
}


predPtr = first;

for ( int i = 1; i < index; i++)
{
predPtr = predPtr->next;
}

if (predPtr != 0)

{
newpointer->next = first->next;
first-> next = newpointer;
size++;

}

else
{
newpointer->next = first;
first = newpointer;
size++;

}

}
It looks like you want to insert the value at a specific index.

This
1
2
3
newpointer->next = first->next;
first-> next = newpointer;
size++;
inserts it always after the first element. Use predPtr instead.

I'd expect this
1
2
3
newpointer->next = first;
first = newpointer;
size++;
within that if ( index == 0) clause. if (first == 0) there too?

If 'predPtr' is 0 is either an error (insert an element at the inappropriate place) or you need the last element and simply add it.

You also need to check whether 'first' is 0
Thank you so much - I really appreciate it. Can you please look at my delete function? I am to delete a value at a given index. I have code below but for some reason, it will not always delete (sometimes it works sometimes it does not).


void List::erase( int index )

{

if (index < 0)
cout << "Invalid index specified";

if (first == NULL)
cout << "No element at specified location";

Node *temp, *newpointer;

temp = first;

if (index == 0)

{
delete first;
}

if (index == 1)

{
temp->next = NULL;

}

else
{
Node *temp;
temp = newpointer->next;
delete temp;

}


}


Thanks so much again!!!

Jen
Well, erase is very much like insert. the if clause and the loop. Just where you link in insert unlink it in erase. Don't forget Size--
Topic archived. No new replies allowed.