题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
思路:一起循环两个链表,将对应位数的数相加 并加上 cur已有的值(考虑到进位问题) 得到cur,cur对10取余就是最后结果现在的位数对应的数。再使cur/10,如果大于9则需要进位,所以必须要 cur += ( l1->val,l2->val)
太久没用C了,,现在开始慢慢回想语法啥的(o(╥﹏╥)o)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int cur=0;
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
while(l1 != NULL || l2 != NULL || cur!=0)
{
if(l1 != NULL)
{
cur += l1->val;
l1 = l1->next;
}
if(l2 != NULL)
{
cur += l2->val;
l2 = l2->next;
}
struct ListNode *p = tail;
tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->val = cur%10;
tail->next = NULL;
cur = cur/10;
if(head == NULL)
{
head = tail;
}
else
{
p->next = tail;
}
}
return head;
}
Python3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = 0
Head = ListNode(0)
p = Head
while(l1 or l2 or cur):
if l1:
cur += l1.val
l1 = l1.next
if l2:
cur += l2.val
l2 = l2.next
p.next = ListNode(cur%10) #???
p = p.next
cur = int(cur/10)
return Head.next