题目链接:
https://leetcode-cn.com/leetbook/read/linked-list/fv6w7/
这道题就是基本的大整数相加,只不过换成了链表的形式
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
newHead->next = NULL;
struct ListNode* p = newHead;
int x = 0;
while(l1 && l2){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = (l1->val+l2->val+x)%10;
p->next = newNode;
p = newNode;
x = (l1->val+l2->val+x) / 10;
l1 = l1->next;
l2 = l2->next;
}
while(l1){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = (l1->val+x)%10;
p->next = newNode;
p = newNode;
x = (l1->val+x) / 10;
l1 = l1->next;
}
while(l2){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = (l2->val+x)%10;
p->next = newNode;
p = newNode;
x = (l2->val+x) / 10;
l2 = l2->next;
}
if(x){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = x;
p->next = newNode;
p = newNode;
}
return newHead->next;
}