leetcode链表--14、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  *     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         int flag = 0;//进位
13         ListNode* tail = new ListNode(0);
14         ListNode* ptr = tail;
15  
16         while(l1 != NULL || l2 != NULL)
17         {
18             int val1 = 0;
19             if(l1 != NULL)
20             {
21                 val1 = l1->val;
22                 l1 = l1->next;
23             }
24  
25             int val2 = 0;
26             if(l2 != NULL)
27             {
28                 val2 = l2->val;
29                 l2 = l2->next;
30             }
31  
32             int tmp = val1 + val2 + flag;
33             ptr->next = new ListNode(tmp % 10);
34             flag = tmp / 10;
35             ptr = ptr->next;
36         }
37         //处理结束了flag还有一个进位则新申请一个为1的结点连入链表
38         if(flag == 1)
39         {
40             ptr->next = new ListNode(1);
41         }
42         return tail->next;
43     }
44 };

 

posted @ 2017-05-26 20:19  qqky  阅读(194)  评论(0编辑  收藏  举报