【LeetCode】2.Add Two Numbers

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

 1 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
 2     int g,s=0,stmp;
 3     struct ListNode *pl,*ptmp,*pi;
 4     pl=NULL;
 5     while(l1&&l2)
 6     {
 7         g=l1->val+l2->val;
 8         g+=s;
 9         stmp=g/10;
10         g%=10;
11         struct ListNode* ptmp=(struct ListNode *)malloc(sizeof(struct ListNode));
12         ptmp->next=NULL;
13         ptmp->val=g;
14         if(pl==NULL)
15             {
16                 pl=ptmp;
17                 pi=pl;
18             }
19             else
20             {
21                 pi->next=ptmp;
22                 pi=pi->next;
23             }
24         s=stmp;
25         l1=l1->next;
26         l2=l2->next;
27     }
28     if(l1==NULL)
29         l1=l2;
30     while(l1)
31     {
32         g=l1->val;
33         g+=s;
34         stmp=g/10;
35         g%=10;
36         struct ListNode *ptmp=malloc(sizeof(struct ListNode));
37         ptmp->next=NULL;
38         ptmp->val=g;
39         pi->next=ptmp;
40         pi=pi->next;
41         s=stmp;
42         l1=l1->next;
43     }
44     if(s)
45     {
46         struct ListNode *ptmp=malloc(sizeof(struct ListNode));
47         ptmp->next=NULL;
48         ptmp->val=s;
49         pi->next=ptmp;
50     }
51     return pl;
52 }

 Python:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def addTwoNumbers(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         tmp = l1
15         up = 0
16         while l1 and l2:
17             l1.val += (l2.val+up)
18             if l1.val > 9:
19                 up = 1
20                 l1.val %= 10
21             else:
22                 up = 0
23             p1,p2 = l1,l2
24             l1,l2 = l1.next,l2.next
25         if not l1 and not l2:
26             if up:
27                 p1.next = ListNode(up)
28                 return tmp
29         if l2:
30             p1.next = l2
31         l1 = p1.next
32         while l1 and up:
33             l1.val += up
34             if l1.val >9:
35                 up=1
36                 l1.val %= 10
37             else:
38                 up = 0
39             p1 = l1
40             l1 = l1.next
41         if up:
42             p1.next = ListNode(up)
43         return tmp
44             
原文地址:https://www.cnblogs.com/fcyworld/p/6146469.html