Originally Posted by
itCbitC
Take any two numbers and see the results for yourself.
I have, which is why I thought it was weird that it's not working for you
Here are the results I get from comparing 11345, 12345 & 107483 against each other.
(manually formatted to look better here on the forums, but otherwise identical to the original output)
Code:
11345 == 11345 : 0
11345 == 12345 : 1
11345 == 107483 : 1
12345 == 11345 : -1
12345 == 12345 : 0
12345 == 107483 : 1
107483 == 11345 : -1
107483 == 12345 : -1
107483 == 107483 : 0
Full source for reference:
Code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct integer
{
int digit;
struct integer* next;
};
struct integer* make_int(const char* strnum)
{
int i, offset = 0;
struct integer *ret, *current, *next;
if(!strnum)
return 0;
while(strnum[offset] == '0')
offset++;
ret = malloc(sizeof(*ret));
ret->digit = 0;
ret->next = 0;
next = ret;
i = strlen(strnum + offset);
while(i)
{
current = next;
current->digit = strnum[--i + offset] - '0';
if(i)
next = malloc(sizeof(*next));
else
next = 0;
current->next = next;
}
return ret;
}
void free_int(struct integer* num)
{
struct integer* current = num;
while(num)
{
current = num;
num = num->next;
free(current);
}
}
void print_int(const struct integer* num)
{
if(num)
{
print_int(num->next);
putchar(num->digit + '0');
}
}
int compare(const struct integer* l, const struct integer* r)
{
/* comparison value */
int comp = 0;
/* test for NULL pointers */
if(!l && !r) return 0;
if(!l) return 1;
if(!r) return -1;
while(1)
{
/* if both numbers are of equal length,
* return the comparison value */
if(!l && !r) return comp;
/* test the length of the numbers */
if(l->next && !r->next) return -1;
if(!l->next && r->next) return 1;
/* compare digits */
if(l->digit < r->digit) comp = 1;
else if(l->digit > r->digit) comp = -1;
/* move to next digit */
l = l->next;
r = r->next;
}
}
void compare_and_print(const struct integer* lhs, const struct integer* rhs)
{
print_int(lhs); printf(" == "); print_int(rhs); printf(" : %d\n", compare(lhs, rhs));
}
int main()
{
struct integer* num1 = make_int("11345");
struct integer* num2 = make_int("12345");
struct integer* num3 = make_int("107483");
compare_and_print(num1, num1);
compare_and_print(num1, num2);
compare_and_print(num1, num3);
compare_and_print(num2, num1);
compare_and_print(num2, num2);
compare_and_print(num2, num3);
compare_and_print(num3, num1);
compare_and_print(num3, num2);
compare_and_print(num3, num3);
free_int(num1);
free_int(num2);
free_int(num3);
return 0;
}