码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2015-10-01 14:02:44      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

 

题目: 

  You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 0 -> 8

 

思路:

  题目比较简单,关键在于用一个变量记录是否有进位即可,同时遍历两个链表,每次将 val 和进位相加,将和的个位存到新的链表,和的十位记录到进位中,直到链表遍历完成。

 

代码:

技术分享
 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     struct ListNode * result = NULL, * last = NULL, *last1 = l1, *last2 = l2;
10     int decade = 0, sum = 0;
11     
12     result = malloc(sizeof(struct ListNode));
13     sum = last1->val + last2->val;
14     result->val = sum % 10;
15     last = result;
16     last1 = last1->next;
17     last2 = last2->next;
18     decade = sum / 10;
19     while (last1 && last2){
20         sum = last1->val + last2->val + decade;
21         last->next = malloc(sizeof(struct ListNode));
22         last = last->next;
23         last->val = sum % 10;
24         decade = sum / 10;
25         last1 = last1->next;
26         last2 = last2->next;
27     }
28     while (last1){
29         last->next = malloc(sizeof(struct ListNode));
30         last = last->next;
31         sum = last1->val + decade;
32         last->val = sum % 10;
33         last1 = last1->next;
34         decade = sum / 10;
35     }
36     while (last2){
37         last->next = malloc(sizeof(struct ListNode));
38         last = last->next;
39         sum = last2->val + decade;
40         last->val = sum % 10;
41         last2 = last2->next;
42         decade = sum / 10;
43     }
44     if (decade == 1){
45         last->next = malloc(sizeof(struct ListNode));
46         last = last->next;
47         last->val = 1;
48     }
49     last->next = NULL;
50     return result;
51 }
Add Two Numbers

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/YaolongLin/p/4850947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!