LeetCode 面试题 02.05. 链表求和

题目链接:https://leetcode-cn.com/problems/sum-lists-lcci/

给定两个用链表表示的整数,每个节点包含一个数位。

这些数位是反向存放的,也就是个位排在链表首部。

编写函数对这两个整数求和,并用链表形式返回结果。

示例:

输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:假设这些数位是正向存放的,请再做一遍。

示例:

输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
10     struct ListNode *q=l1,*p=l2,*cur,*pre;
11     int len1=0,len2=0,len=0;
12     while(q){
13         len1++;
14         q=q->next;
15     }
16     while(p){
17         len2++;
18         p=p->next;
19     }
20     int flag=0;
21     if(len1>len2){
22         q=l1;
23         p=l2;
24         flag=1;
25     }else{
26         q=l2;
27         p=l1;
28         flag=0;
29     }
30     int car=0,x,y;
31     while(q){
32         x=q?q->val:0;
33         y=p?p->val:0;
34         q->val=(x+y+car)%10;
35         car=(x+y+car)/10;
36         pre=q;
37         if(q) q=q->next;
38         if(p) p=p->next;
39     }
40     if(car){
41         struct ListNode *tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
42         tmp->val=car;
43         tmp->next=NULL;
44         pre->next=tmp;
45     }
46     return flag?l1:l2;
47 }

猜你喜欢

转载自www.cnblogs.com/shixinzei/p/12400602.html