LeetCode.002 Add Two Numbers

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

题意

给你两个链表,求出这两个链表所代表数字的和。

链表2 -> 4 -> 3 代表数字 324,链表5 -> 6 -> 4代表数字465,求出和的结果也用链表倒序表示。

思路

1.两个链表都从头节点开始依次相加,相加节点的个位数保存在新节点中,进位保存在carry中。

2.如果某一个链表遍历完了,则另一个链表和carry接着相加,直到遍历完。

3.要注意的是最后的进位(carry)如果等于1,则还需要新建立个节点存储此进位,再添加到结果链表的尾部就可以了。

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

 

posted @ 2015-07-18 19:54  Mad.King  阅读(95)  评论(0)    收藏  举报