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

思路:

从头到后的顺序,注意有进位,一个小技巧就是先是在程序判断两边都还有数字,均不为空,再判断谁已经“ 出局 ”。

 

代码:

/**
 * 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 *dummy=new ListNode(0);
        ListNode *tail=dummy;
        int flag=0;
        
        while(l1||l2){
            int m=0;
            if(l1){
                m+=l1->val;
                l1=l1->next;
            }
            
            if(l2){
                m+=l2->val;
                l2=l2->next;
            }
            m=m+flag;
            
            ListNode *tmp=new ListNode(m%10);
            flag=m/10;
            tail->next=tmp;
            tail=tail->next;
        }
        
        if(flag){
            ListNode *tmp=new ListNode(flag);
            tail->next=tmp;
        }
        return dummy->next;
    }
};


 

 

posted @ 2015-12-05 23:51  JSRGFJZ6  阅读(103)  评论(0编辑  收藏  举报