77 lines
1.5 KiB
C
77 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct _st_node {
|
|
struct _st_node *next;
|
|
int val;
|
|
} st_node;
|
|
|
|
|
|
st_node *node_alloc(int val, st_node *next)
|
|
{
|
|
st_node *node = (st_node *)malloc(sizeof (st_node));
|
|
node->next = next;
|
|
node->val = val;
|
|
return node;
|
|
}
|
|
|
|
st_node *node_sum_r(int carry_up, st_node *p, st_node *q)
|
|
{
|
|
if (p) carry_up += p->val;
|
|
if (q) carry_up += q->val;
|
|
if (!p && !q && !carry_up) return 0;
|
|
return node_alloc(carry_up % 10,
|
|
node_sum_r(carry_up / 10,
|
|
p ? p->next : 0,
|
|
q ? q->next : 0));
|
|
}
|
|
|
|
st_node *node_sum(st_node *p, st_node *q)
|
|
{
|
|
if (!p || !q) {
|
|
return 0;
|
|
}
|
|
return node_sum_r(0, p, q);
|
|
}
|
|
|
|
st_node *str_to_node(char *num)
|
|
{
|
|
st_node *node = 0;
|
|
for (; *num; num++) {
|
|
st_node *new = node_alloc(*num - '0', 0);
|
|
new->next = node;
|
|
node = new;
|
|
}
|
|
return node;
|
|
}
|
|
|
|
int node_len(st_node *node)
|
|
{
|
|
int len = 0;
|
|
for (; node; node = node->next) len += 1;
|
|
return len;
|
|
}
|
|
|
|
void node_show(st_node *node)
|
|
{
|
|
int len = node_len(node);
|
|
char *buf = (char *)malloc(len + 1);
|
|
char *p = buf + len;
|
|
*p-- = 0;
|
|
for (; node; node = node->next) {
|
|
*p-- = node->val + '0';
|
|
}
|
|
printf("%s\n", buf);
|
|
free(buf);
|
|
return;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
st_node *l1 = str_to_node("99");
|
|
st_node *l2 = str_to_node("9999");
|
|
st_node *ls = node_sum(l1, l2);
|
|
node_show(ls);
|
|
return 0;
|
|
}
|