leetcode题目-求两相加
2.两数相加
给出两个非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
解题:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
static void showNode(struct ListNode* head){
while (head){
printf("%d->", head->val);
head = head->next;
}
}
/**
* 两数相加
* @param l1
* @param l2
* @return
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
struct ListNode* temp1 = l1;
struct ListNode* temp2 = l2;
// 是否进位
int isCarry = 0;
struct ListNode* head = NULL;
struct ListNode* current = NULL;
struct ListNode* currentPre = NULL;
int num = 0;
while (temp1 && temp2){
num = temp1->val + temp2->val + isCarry;
current = (struct ListNode*)malloc(sizeof(struct ListNode));
if(currentPre!= NULL){
currentPre->next = current;
}
if(head == NULL){
head = current;
}
if(num >= 10){
num = num-10;
isCarry = 1;
}else {
isCarry = 0;
}
current->val = num;
current->next = NULL;
temp1 = temp1->next;
temp2 = temp2->next;
currentPre = current;
}
while (temp1){
num = temp1->val + isCarry;
current = (struct ListNode*)malloc(sizeof(struct ListNode));
currentPre->next = current;
if(num >= 10){
num = num-10;
isCarry = 1;
}else {
isCarry = 0;
}
current->val = num;
current->next = NULL;
temp1 = temp1->next;
currentPre = current;
}
while (temp2){
num = temp2->val + isCarry;
current = (struct ListNode*)malloc(sizeof(struct ListNode));
currentPre->next = current;
if(num >= 10){
num = num-10;
isCarry = 1;
}else {
isCarry = 0;
}
current->val = num;
current->next = NULL;
temp2 = temp2->next;
currentPre = current;
}
if(isCarry){
current = (struct ListNode*)malloc(sizeof(struct ListNode));
currentPre->next = current;
current->val = 1;
current->next = NULL;
}
return head;
}
int main(){
struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 1;
l2->val = 2;
struct ListNode* temp1 = l1;
struct ListNode* temp2 = l2;
for(int i = 0; i < 3; i++){
temp1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
temp2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
temp1->next->val = i+6;
temp1->next->next = NULL;
temp2->next->val = i+6;
temp2->next->next = NULL;
temp1 = temp1->next;
temp2 = temp2->next;
}
showNode(addTwoNumbers(l1, l2));
return 0;
}