码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 2 Add two numbers

时间:2015-06-18 00:44:59      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

    
<span style="font-size:14px;">/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {

public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
     
          if(l1 == NULL )
              return l2;
          if(l2 == NULL )
              return l1;
          if(l1 == NULL && l2 == NULL ) 
              return NULL;
          ListNode * head = NULL;
          ListNode * preo = NULL;
          int Y =  0;
          while( l1 && l2 )
          {
              int tmp = l1->val + l2->val + Y;
              Y=tmp/10;
              int Val=tmp%10;  
              ListNode* Node = new ListNode(tmp);
              Y= Node->val / 10;
              Node->val %= 10;
              if(head == NULL)
                head = Node;
              else 
               preo->next = Node;
              preo = Node;
             l1=l1->next;
             l2=l2->next;       
          }     
           
          while(l1)
          { 
            int tmp = l1->val+Y;
            Y=tmp/10;
            int Val = tmp%10;
            ListNode* Node = new ListNode(Val);
            if( head == NULL )
              head = Node;
            else
             preo->next = Node;
             preo = Node;
            l1=l1->next; 
          }
        
          while(l2)
          {
            int tmp = l2->val+Y;
            Y=tmp/10;
            int Val = tmp%10;
            ListNode* Node = new ListNode(Val);
            if( head == NULL )
              head = Node;
            else
             preo->next = Node;
             preo = Node;
            
            l2=l2->next;
          }
           
          if(Y!=0)
          {
             ListNode* Node = new ListNode(1);
             preo->next = Node;
             
          }        
          
          return head;
       }
  };</span>



感触:  有指针操作时一定要小心 = 和 == ,  我好粗心啊..

leetcode 2 Add two numbers

标签:

原文地址:http://blog.csdn.net/nizhannizhan/article/details/46540483

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!