Re: Link List Question
Re: Link List Question
- Subject: Re: Link List Question
- From: email@hidden
- Date: Sun, 15 Dec 2002 12:05:59 +0100
On dimanche, dicembre 15, 2002, at 04:41 AM, Wesley Penner wrote:
Hi,
I'm playing with a Obj-c class implementation of a link list (just to
get the hang of it, really). I want to divide a link list of random
integers into two lists, one odd and the other even. The odd (second)
part of the separation process goes smoothly, but after going through
the even side and picking up the next value, the program calls
"EXC_BAD_ACCESS." Since the two parts of the switch statement are
identical, I can't figure out why this should be. Can someone please
shed some light on my darkness? The pertinent (impertinent? ;)) code is
below.
Note: WSLink is a class implementation of a link list, with (int)value
and (WSLink)next variables and accessor methods, as well as a
+randomListGenerator:(int)size method which returns a list with random
values.
- (void)oddEven {
WSLink *odd, *even,
*o = odd, *e=even,
odd, even, o and e are not initialized before being used.
*alist = [WSLink randomListGenerator:100], *x = alist,
*temp;
// set alist as random list of 100 items, odd & even as
heads for new lists,
// o, e & x are transversal variables.
// temp is for pointing to the node that will be moved
from
main to sub lists
while ( [x next] != NULL ) {
temp = [x next]; // temp points to next main list value
switch ( [temp value]%2 ) {
case 0:
[x setNext:[[x next] next]]; // set next main list
value beyond temp
[e setNext:temp]; // set next even item to temp
=> crash
e = [e next]; // advance pointer to end of even list
break;
case 1:
[x setNext:[[x next] next]]; // same as above, but for
odd
[o setNext:temp];
=> crash
o = [o next];
break;
}
[temp setNext:NULL]; // Set the end of the list (odd/even) to
NULL
}
}
Also, if anyone has ideas for stream-lining the code, or using linked
lists with Obj-C I'd appreciate the feedback!
It could look like this:
- (void)oddEven
{
WSLink *odd, *even,
*o, *e,
*alist = [WSLink randomListGenerator:100], *x = alist,
*temp;
odd= [WSLink new];
even = [WSLink new];
o=ood;
e=even;
while ( [x next] != nil )
{
temp = [x next]; // temp points to next main list value
[x setNext:[temp next]];
[temp setNext: nil];
if (([temp value] & 0x1) == 0)
{
[e setNext:temp];
e = [e next];
}
else
{
[o setNext:temp];
o = [o next];
}
}
}
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.