两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
考虑若链表不等长,即用0补足不等的长度,最后注意最高位的进位
#include<cstdio>
#include<cstring>
#include<iostream>
#include<malloc.h>
using namespace std ;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void print(struct ListNode* head){
head = head->next ;
while(head){
cout<<head->val<<" " ;
head = head->next ;
}
cout<<endl ;
return ;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *pre = new ListNode(0) ;
ListNode *cur , *head;
head = cur = pre ;
int sum = 0 ;
while(l1 || l2){
int x = l1 == NULL ? 0 : l1->val ;
int y = l2 == NULL ? 0 : l2->val ;
cur = new ListNode((x + y + sum)%10) ;
sum = (x + y + sum)/10 ;
pre->next = cur ;
pre = cur ;
if(l1 != NULL)l1=l1->next ;
if(l2 != NULL)l2=l2->next ;
}
if(sum) {
cur = new ListNode(sum) ;
pre->next = cur ;
pre = cur ;
}
pre->next = NULL ;
return head -> next;
}
};
struct ListNode* createList(){
int num ;
struct ListNode *head , *p1 , *p ;
head = p1 = p = (struct ListNode *)malloc(sizeof(struct ListNode)) ;
while(scanf("%d",&num) && num != -1)
{
p = (struct ListNode *)malloc(sizeof(struct ListNode)) ;
p->val = num ;
p->next = NULL ;
p1->next = p ;
p1 = p ;
}
return head ;
};
int main()
{
struct ListNode *head1 , *head2 ;
head1 = createList() ;
head2 = createList() ;
print(head1) ;
print(head2) ;
Solution a ;
head1 = a.addTwoNumbers(head1->next,head2->next) ;
print(head1) ;
return 0 ;
}