leetcode 力扣 hot100 两数想加 C语言
暴力破解:
倒序相加,有进位计数。
tail指针的作用是连接计数链表的上下节点。
C语言中创建新的链表节点就是重新malloc一块节点内存,在同一个指针上进行第二次malloc时指针会指向新地址,为防止旧地址丢失,所以用tail指针连接前后节点。
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* List = NULL;
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
int yu = 0,chu = 0,sum = 0;
while(l1 != NULL || l2 != NULL)
{
sum = 0;
sum += chu;
if(l1 == NULL)
{
sum += 0;
}
else
{
sum += l1->val;
}
if(l2 == NULL)
{
sum += 0;
}
else
{
sum += l2->val;
}
yu = sum%10;
chu = sum/10;
List = (struct ListNode*)malloc(sizeof(struct ListNode));
List->val = yu;
List->next = NULL;
if(!head)
{
head = List;
tail = List;
}
else
{
tail->next = List;
tail = List;
}
if(l1 != NULL) l1 = l1->next;
if(l2 != NULL) l2 = l2->next;
}
if(chu == 1)
{
List= (struct ListNode*)malloc(sizeof(struct ListNode));
List->val = chu;
List->next = NULL;
tail->next = List;
tail = List;
}
return head;
}

浙公网安备 33010602011771号