2. Add Two Numbers(两数相加)

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
 9     
10     int num1 = 0;
11     int num2 = 0;
12     int high_res = 0;
13     struct ListNode *tail = NULL; /*尾指针*/
14     struct ListNode *head = NULL;/*头指针*/
15     int is_head = 1;
16 
17     while(l1 != NULL || l2 != NULL || low_res != 0){
18         if(l1){
19             num1 = l1->val;
20             l1 = l1->next;
21         }
22         
23          if(l2){
24            num2 = l2->val;
25            l2= l2->next;
26         }
27         
28         struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
29         node->next = NULL;
30        
31        /*获取高位数*/
32         node->val = (num1+num2+high_res)%10;
33         if(is_head){
34             head = node;
35             tail = node;
36             is_head = 0;
37         }else{
38             tail->next = node;
39             tail = tail->next;
40             
41         }
42         /*获取高位数*/
43         high_res = (num1+num2+low_res)/10;
44         num1 = 0;
45         num2= 0;    
46         
47     }
48 
49     return head;
50     
51 }

 

转载于:https://www.cnblogs.com/bspp1314/p/9392117.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值