[容易]链表求和

题目来源:http://www.lintcode.com/zh-cn/problem/add-two-numbers/

思想是用一个carry同时更新和与进位。出现过以下问题。
1、new节点的时候需要判断,否则最终会多出一个0节点。
2、起初用do while,但也是错的。而且while最后要加;。
3、判断是否需要new节点,不一定是carry!=0,carry是和和进位的变量。

 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     /*
12      * @param l1: the first list
13      * @param l2: the second list
14      * @return: the sum list of l1 and l2 
15      */
16     ListNode *addLists(ListNode *l1, ListNode *l2) {
17         // write your code here
18         ListNode *temp1=l1;//temp1指向l1首节点
19         ListNode *temp2=l2;//temp2指向l2首节点
20         ListNode *head=new ListNode(0);//定义一个新节点ListNode,head指向它
21         ListNode *temp3=head;//temp3指向新链表的首节点
22         int carry=0;//作为进位和元素和的变量
23 
24         while(1)
25         {
26             if(temp1!=NULL)//l1不指向空节点
27             {
28                 carry=carry+temp1->val;
29                 temp1=temp1->next;//指针向后挪一位
30             }
31             if(temp2!=NULL)//l2不指向空节点
32             {
33                 carry=carry+temp2->val;
34                 temp2=temp2->next;//指针向后挪一位
35             }
36             temp3->val=carry%10;//把和的个位放到新链表
37             carry=carry/10;//carry更新为进位数,作为下一次相加的进位
38 
39             if(temp1!=NULL||temp2!=NULL||carry!=0)//不能不判断直接new,否则会多一个节点0
40             {
41                 temp3->next=new ListNode(0);//这句话非常重要,如果直接temp3=temp3->next;,最终head只有一个节点,里面是最后一次相加的元素
42                 temp3=temp3->next;//指针向后挪一位
43             }
44             else
45                 break; //循环结束条件,否则死循环
46         }
47         return head;
48     }
49 };
posted @ 2016-04-19 14:52  Pearl_zju  阅读(328)  评论(0编辑  收藏  举报