标签:
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
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12 ListNode *p1,*p2,*p3,*l3,*node;
13 int add,temp;
14
15 p1 = l1;
16 p2 = l2;
17 add = temp = 0;
18 node = new ListNode(0);
19 temp += p1->val + p2->val;
20 if(temp>=10)
21 {temp = temp-10;add++;}
22 node->val = temp;
23 l3 = p3 = node;
24 p1 = p1->next;
25 p2 = p2->next;
26 while(p1!=NULL || p2!= NULL)
27 {
28 temp = add;
29 if(p1!=NULL) temp += p1->val;
30 if(p2!=NULL) temp += p2->val;
31 if(temp>=10)
32 {
33 p3->next = new ListNode(temp-10);
34 add=1;
35 }
36 else{
37 p3->next = new ListNode(temp);
38 add=0;
39 }
40 if(p1!= NULL) p1 = p1->next;
41 if(p2!= NULL) p2 = p2->next;
42 p3 = p3->next;
43 }
44 if(add)
45 {
46 p3->next = new ListNode(add);
47 }
48 return l3;
49 }
50 };
标签:
原文地址:http://www.cnblogs.com/albertarmstrong/p/4696413.html