2010-09-15, 06:10 PM
Digitwise comparison is pretty simple but I'm too lazy to read your code.
Initialize to "equal"
Current digit the same -> keep any previous results
Current digit higher in one number -> that number has 'advantage' (ex. 19 vs. 20 - 2 > 1 so the second is larger, lower digits don't matter)
One has nonzero digits, other doesn't -> return, that number is bigger
Both have zero digits -> return advantage or equal
Killing trailing zeros is pretty easy with a higher level keeping track of pointers
a -> last non-zero LL item
b -> current LL item
Iterate b through the linked list, updating a when you find non-zeros. Then when you reach the end, set the current 'a' to have a null pointer.
As for why your code acts up when they're equal length - P is null, so it breaks from the loop without checking if Q is also null. while(p != null && q != null) would fix this, though you'd have to add a line checking if p == NULL inside the loop.
Alternative approach, because recursion is sexier than while loops:
Initialize to "equal"
Current digit the same -> keep any previous results
Current digit higher in one number -> that number has 'advantage' (ex. 19 vs. 20 - 2 > 1 so the second is larger, lower digits don't matter)
One has nonzero digits, other doesn't -> return, that number is bigger
Both have zero digits -> return advantage or equal
Killing trailing zeros is pretty easy with a higher level keeping track of pointers
a -> last non-zero LL item
b -> current LL item
Iterate b through the linked list, updating a when you find non-zeros. Then when you reach the end, set the current 'a' to have a null pointer.
As for why your code acts up when they're equal length - P is null, so it breaks from the loop without checking if Q is also null. while(p != null && q != null) would fix this, though you'd have to add a line checking if p == NULL inside the loop.
Alternative approach, because recursion is sexier than while loops:
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;
}
