Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linked Lists in C
#9
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:
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;
}
Reply


Messages In This Thread
Linked Lists in C - by Sivrat - 2010-09-14, 02:38 PM
Linked Lists in C - by Fiel - 2010-09-14, 02:41 PM
Linked Lists in C - by Sivrat - 2010-09-14, 02:50 PM
Linked Lists in C - by Fiel - 2010-09-14, 03:00 PM
Linked Lists in C - by Stereo - 2010-09-14, 09:37 PM
Linked Lists in C - by Sivrat - 2010-09-15, 11:54 AM
Linked Lists in C - by Stereo - 2010-09-15, 03:44 PM
Linked Lists in C - by Sivrat - 2010-09-15, 05:29 PM
Linked Lists in C - by Stereo - 2010-09-15, 06:10 PM
Linked Lists in C - by Sivrat - 2010-09-15, 07:49 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:10 PM
Linked Lists in C - by Sivrat - 2010-09-15, 08:17 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:39 PM
Linked Lists in C - by Sivrat - 2010-09-15, 08:45 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:54 PM
Linked Lists in C - by Sivrat - 2010-09-15, 09:02 PM
Linked Lists in C - by Sivrat - 2010-09-15, 10:56 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)