Re: Link List Question
Re: Link List Question
- Subject: Re: Link List Question
- From: Gregory Weston <email@hidden>
- Date: Sun, 15 Dec 2002 09:11:15 -0500
On 12/14/02 at 10:00 PM, Wesley Penner <email@hidden> 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.
>
>
- (void)oddEven {
>
WSLink *odd, *even,
It would appear that odd and even never actually get any storage allocated to
them.
>
*o = odd, *e=even,
>
*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
What about the first value? Or is the head node not used for data storage?
>
switch ( [temp value]%2 ) {
>
case 0:
>
[x setNext:[[x next] next]]; // set next main list
>
value beyond temp
This line (above) is duplicated in both cases of the switch.
>
[e setNext:temp]; // set next even item to temp
And again: Even if "even" had some storage, it looks like the head node is
garbage. Since it never did get assigned any space, I'd say any time you didn't
crash in testing was sheer luck, rooted in the way your variables were laid out
above.
I think what you probably intended, but forgot, to do is initialize odd and even
to NULL and then as you walk alist you should check for that nullness as you're
building the lists (in which case the node you're examining becomes the head of
the appopropriate sub-list).
>
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];
>
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!
Well, my first idea would be: why reinvent the wheel? There are already decent
collection classes available. If you're getting used to the language, fine, but
for actually usage, concentrate on creating new functionality.
G
_______________________________________________
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.