Add Two Numbers

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if(NULL == l1) return l2; 
        if(NULL == l2) return l1;
        
        ListNode* p1 = l1,*p2 = l2;
        ListNode *ret = NULL;ListNode *p = NULL;
        int sign = 0;
        while(NULL != p1 || NULL != p2) ///用这种方法,就多么完整,没有补补修修
        {
          if(p1 == l1)
          {
            ListNode *ret = new ListNode(0);
            p = ret;
          }else{
              p->next = new ListNode(0);
              p = p->next;  ///老师忘记这一步
          }///这样就完成了直到最后的新建工作~

          if(NULL != p1 && NULL != p2)
          {
              int val = p1->val + p2->val + sign;
              p->val = val%10;
              sign = val/10;
              p1 = p1->next;
              p2 = p2->next;
          }
          else if(NULL == p1 && NULL != p2)
          {
              int val = p2->val + sign;
              p->val = val%10;
              sign = val/10;
              p2 = p2->next;
          }
          else if(NULL != p1 && NULL == p2)
          {
              int val = p1->val + sign;
              p->val = val%10;
              sign = val/10;
              p1 = p1->next;
          }
        }
        
        if(sign == 1)
            p->next = new ListNode(1);
        return ret;
    }
};

 

posted on 2014-05-28 20:21  berkeleysong  阅读(170)  评论(0编辑  收藏  举报

导航