【LeetCode】2.Add Two Numbers

时间:2024-12-10 00:06:14

首先想到的是走到其中一个链表的尽头,然后把剩余的链表中的值放入写的链表,返回,但是自己写的代码好长。

 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int g,s=,stmp;
struct ListNode *pl,*ptmp,*pi;
pl=NULL;
while(l1&&l2)
{
g=l1->val+l2->val;
g+=s;
stmp=g/;
g%=;
struct ListNode* ptmp=(struct ListNode *)malloc(sizeof(struct ListNode));
ptmp->next=NULL;
ptmp->val=g;
if(pl==NULL)
{
pl=ptmp;
pi=pl;
}
else
{
pi->next=ptmp;
pi=pi->next;
}
s=stmp;
l1=l1->next;
l2=l2->next;
}
if(l1==NULL)
l1=l2;
while(l1)
{
g=l1->val;
g+=s;
stmp=g/;
g%=;
struct ListNode *ptmp=malloc(sizeof(struct ListNode));
ptmp->next=NULL;
ptmp->val=g;
pi->next=ptmp;
pi=pi->next;
s=stmp;
l1=l1->next;
}
if(s)
{
struct ListNode *ptmp=malloc(sizeof(struct ListNode));
ptmp->next=NULL;
ptmp->val=s;
pi->next=ptmp;
}
return pl;
}

Python:

 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
tmp = l1
up = 0
while l1 and l2:
l1.val += (l2.val+up)
if l1.val > 9:
up = 1
l1.val %= 10
else:
up = 0
p1,p2 = l1,l2
l1,l2 = l1.next,l2.next
if not l1 and not l2:
if up:
p1.next = ListNode(up)
return tmp
if l2:
p1.next = l2
l1 = p1.next
while l1 and up:
l1.val += up
if l1.val >9:
up=1
l1.val %= 10
else:
up = 0
p1 = l1
l1 = l1.next
if up:
p1.next = ListNode(up)
return tmp