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

[LeetCode] Add Two Numbers

时间:2014-06-28 10:45:34      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   os   

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

/**
 * 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) {
        ListNode *head = l1;
        int flag = 0;
        ListNode *li1 = new ListNode(0);
        ListNode *li2 = new ListNode(0);
        li1->next = l1;
        li2->next = l2;

        while(li1->next!=NULL && li2->next!=NULL)
        {
            li1->next->val = li1->next->val+li2->next->val+flag;
            if(li1->next->val>9)
            {
                li1->next->val = li1->next->val-10;
                flag = 1;
            }
            else
            {
                flag = 0;
            }
            li1 = li1->next;
            li2 = li2->next;
        }
        while(li1->next != NULL && li2->next == NULL)
        {
            if(flag==1 && li1->next->val<9)
             {
                 ++li1->next->val;
                 flag = 0;
             }
             else if(flag==1 && li1->next->val==9)
             {
                 li1->next->val = 0;
                 flag = 1;
             }
            li1=li1->next;
        }
        while(li2->next != NULL && li1->next == NULL)
        {
            ListNode *p1;
             if(flag==1 && li2->next->val<9)
             {
                 p1 = new ListNode(li2->next->val+1);
                 flag = 0;
             }
             else if(flag==1 && li2->next->val==9)
             {
                 p1 = new ListNode(0); 
                 flag = 1;
             }
             else
             {
               p1 = new ListNode(li2->next->val);
             }
             li1->next =p1;
            li1 = li1->next;  
            li2 = li2->next;
        }
        if(flag == 1)
        {
            ListNode *p = new ListNode(1);
            li1->next = p;
            
        }
        return head;
    }
    
};

 

[LeetCode] Add Two Numbers,布布扣,bubuko.com

[LeetCode] Add Two Numbers

标签:des   style   blog   color   strong   os   

原文地址:http://www.cnblogs.com/Xylophone/p/3804166.html

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