double linked list
Feb 21, 2010 at 10:34pm UTC
im trying to create a doublely linked list of objects and am having trouble getting it to actually insert the data. the program runs but seg faults every time it trys to insert the second item into the list. all the main program is doing is sending the methods the item data so that i can be put in the list. ive tracked down the error to one of these two methods.
thnaks for the help
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
ListNode *List::find(int index) const
{
if ( (index < 1) || (index > getLength()) )
return NULL;
else // count from the beginning of the list.
{ if (index < size /2)
{
ListNode *cur = head;
ListNode *previous = NULL;
for (int skip = 1; skip < index; ++skip)
cur = cur->next;
previous = cur -> prev;
return cur;
}
else
{
ListNode *cur = tail;
ListNode *previous = NULL;
for (int skip = 1; skip < index; --skip)
cur = cur -> prev;
previous = cur -> prev;
}
} // end if
void List::insert(int index, const ListItemType& newItem)
throw (ListIndexOutOfRangeException, ListException)
{
int newLength = getLength() + 1;
if ( (index < 1) || (index > newLength) )
throw ListIndexOutOfRangeException(
"ListIndexOutOfRangeException: insert index out of range" );
else
{ // try to create new node and place newItem in it
try
{
ListNode *newPtr = new ListNode;
size = newLength;
newPtr->item = newItem;
// attach new node to list
if (index == 1)
{ // insert new node at beginning of list
newPtr->next = head;
head = newPtr;
newPtr ->prev = NULL;
newPtr ->item = newItem;
}
else
{ ListNode *previous = find(index-1);
ListNode * after = find(index + 1);
// insert new node after node
// to which prev points
newPtr->next = previous -> next;
previous -> next = newPtr;
after -> prev = newPtr;
newPtr -> prev = previous;
} // end if
} // end try
catch (bad_alloc e)
{
throw ListException(
"ListException: memory allocation failed on insert" );
} // end catch
} // end if
} // end insert
Feb 22, 2010 at 8:52am UTC
just check n verify the code in bold:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
if (index < size /2)
{
ListNode *cur = head;
ListNode *previous = NULL;
for (int skip = 1; skip < index; ++skip)
cur = cur->next;
previous = cur -> prev;
return cur;
}
else
{
ListNode *cur = tail;
ListNode *previous = NULL;
for (int skip = 1; skip < index; --skip)
cur = cur -> prev;
previous = cur -> prev;
}
It should be
for (int skip = size; skip < index; --skip)
Feb 22, 2010 at 10:54am UTC
also you are missing on of the closing braces of the find function. please check .
Topic archived. No new replies allowed.