給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
void* insert_tail(struct ListNode* head,int val)
{
if(!head){
return NULL;
}
struct ListNode *tmp_new_node = NULL,*tmp_p = head,*tmp_q = NULL;
tmp_new_node = (struct ListNode *)malloc(sizeof(struct ListNode) );
if(!tmp_new_node){
return NULL;
}
tmp_new_node->val = val;
tmp_new_node->next = NULL;
while(tmp_p->next){
tmp_p = tmp_p->next;
}
tmp_p->next = tmp_new_node;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *p = l1->next,*q = l2->next,*new_head = NULL;
int add = 0,add_one = 0;
new_head = (struct ListNode *)malloc(sizeof(struct ListNode) );
if(!new_head){
return NULL;
}
new_head->next = NULL;
while(p && q){
add = p->val + q->val + add_one;
if(add >= 10){
add -= 10;
add_one = 1;
}else{
add_one = 0;
}
p = p->next;
q = q->next;
insert_tail(new_head,add);
}
if(!p && q){
while(q){
add = q->val + add_one;
if(add >= 10){
add -= 10;
add_one = 1;
}else{
add_one = 0;
}
q = q->next;
insert_tail(new_head,add);
}
}else if(p && !q){
while(p){
add = p->val + add_one;
if(add >= 10){
add -= 10;
add_one = 1;
}else{
add_one = 0;
}
p = p->next;
insert_tail(new_head,add);
}
}
if(add_one == 1){
insert_tail(new_head,1);
}
return new_head;
}
struct ListNode * init_head(struct ListNode *head)
{
head = (struct ListNode *)malloc(sizeof(struct ListNode) );
if(!head){
return NULL;
}
else{
head->next = NULL;
}
return head;
}
void insert_node(struct ListNode *head,int val)
{
if(!head){
return ;
}
struct ListNode *p = head,*new_node = NULL;
new_node = (struct ListNode *)malloc(sizeof(struct ListNode) );
if(!new_node){
return ;
}
new_node->val = val;
new_node->next = p->next;
p->next = new_node;
}
void print_list(struct ListNode *head)
{
if(!head){
return ;
}
struct ListNode *p = head->next;
while(p){
printf("%d\n",p->val);
p = p->next;
}
printf("--------------------------------\n");
}
void free_list(struct ListNode *head)
{
if(!head){
return ;
}
struct ListNode *p = head->next,*q = NULL;
while(p){
q = p->next;
free(p);
p = q;
}
free(head);
}
int main()
{
struct ListNode *l1 = NULL,*l2 = NULL;
l1 = init_head(l1);
insert_node(l1,3);
insert_node(l1,4);
insert_node(l1,2);
print_list(l1);
l2 = init_head(l2);
insert_node(l2,4);
insert_node(l2,6);
insert_node(l2,5);
print_list(l2);
struct ListNode* ret = addTwoNumbers(l1,l2);
print_list(ret);
free_list(l1);
free_list(l2);
free_list(ret);
return 0;
}