2. 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

 

 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 *phead;
10     struct ListNode *cur1;
11     struct ListNode *cur2;
12     struct ListNode *curp;
13     struct ListNode *dele;
14     struct ListNode *pnew;
15     phead = NULL;
16     cur1 = l1;
17     cur2 = l2;
18     int flag = 0;
19     while(cur1 != NULL || cur2 != NULL)
20     {
21          if(phead == NULL)
22          {
23              curp = (struct ListNode *)malloc(sizeof(struct ListNode));
24              memset(curp,0,sizeof(struct ListNode));
25              phead = curp;
26          }
27          else
28          {
29              pnew = (struct ListNode *)malloc(sizeof(struct ListNode));
30              memset(pnew,0,sizeof(struct ListNode));
31              curp->next = pnew;
32              curp = pnew;
33          }
34         if(cur1 == NULL)
35         {
36             curp->val = (cur2->val + flag) % 10;
37             flag = (cur2->val + flag) / 10;
38             dele = cur2;
39             cur2 = cur2->next;
40             free(dele);
41             dele = NULL;
42         }
43         else if(cur2 == NULL)
44         {
45             curp->val = (cur1->val + flag) % 10;
46             flag = (cur1->val + flag) / 10;
47             dele = cur1;
48             cur1 = cur1->next;
49             free(dele);
50             dele = NULL;
51         }
52         else
53          {
54             curp->val = (cur1->val + flag + cur2->val) % 10;
55             flag = (cur1->val + flag + cur2->val) /10;
56             dele = cur2;
57             cur2 = cur2->next;
58             free(dele);
59             dele = NULL;
60             dele = cur1;
61             cur1 = cur1->next;
62             free(dele);
63             dele = NULL;
64          }
65          
66     }
67     if(flag == 1)                            //最后要注意进位的问题!!!
68     {
69         pnew = (struct ListNode *)malloc(sizeof(struct ListNode));
70         memset(pnew,0,sizeof(struct ListNode));
71         curp->next = pnew;
72         pnew->val = 1;
73         return phead;
74     }
75     return phead;
76 }

 

posted @ 2016-05-24 21:36  米开朗菠萝  阅读(225)  评论(0编辑  收藏  举报