2010-09-15, 08:10 PM
Okay, took the time to look at the spec for how that should behave so I can get the signs right >_>
p < q: -1
p = q: 0
p > q: 1
Since it's recursive it goes through from the most significant digit, so for example 4000 vs 5555
p = null & q = null -> return 0
p = 4, q = 5, c = 0 -> return -1
p = 0, q = 5, c = -1 -> return c = -1 (repeat x3)
return -1
Since 4000 < 5555 this seems to be returning the correct value of -1.
Whereas your code,
again, 4000 vs. 5555
p=0, q=5 -> j = -1 (repeat x3)
p=4, q=5 -> j = -1
now p == null so it should break out of the while loop and return j=-1.
I'm not sure what you have differently but this seems like it would work correctly?
p < q: -1
p = q: 0
p > q: 1
Code:
compare (*p, *q) {
if (p == null) return -1;
if (q == null) return 1;
// or vice versa
if (p->next != null && q -> next != null) {
c = compare(p->next, q->next)
if (c == 0) {
if (p > q) return 1;
if (q > p) return -1;
else return 0;
}
else return c;
}
else return 0;
}p = null & q = null -> return 0
p = 4, q = 5, c = 0 -> return -1
p = 0, q = 5, c = -1 -> return c = -1 (repeat x3)
return -1
Since 4000 < 5555 this seems to be returning the correct value of -1.
Whereas your code,
Code:
int compare(struct integer *p, struct integer *q)
{
int j;
while (p != NULL){
if(q==NULL){
return 1;}
else if (q!=NULL){
if (p>q){
j=1;}
else if (p<q){
j= -1;}
else if (p==q){
j= 0;}
}
p= p->next;
q= q->next;
}
return (j);
}p=0, q=5 -> j = -1 (repeat x3)
p=4, q=5 -> j = -1
now p == null so it should break out of the while loop and return j=-1.
I'm not sure what you have differently but this seems like it would work correctly?

