T2_两数相加

方法1: 同时遍历两个链表,两个链表同时一对一相加,超过10就加到下一个加法集合。

/**
 * 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* p=new ListNode(-1);//建立一个结点
        ListNode* h=p;//指针
        int sum=0;//两数相加
        bool carry=false;//判断是否需要进1
        while(l1!=NULL || l2!=NULL){
               sum=0;
            if(l1!=NULL){
                sum+=l1->val;//遍历链表l1
                l1=l1->next;
            }
            
            if(l2!=NULL){
                sum+=l2->val;//遍历链表l2
                l2=l2->next;
            }
            if(carry){
                sum++;//carry第一对加法是false;第二对加法才需要判断
            }
           // sum=sum>=10?sum-10:sum;
            
            h->next=new ListNode(sum%10);
            h=h->next;
            carry=sum>=10?true:false;

        }
        if(carry){
            h->next=new ListNode(1);
        }
        return p->next;//第一个结点值为-1,,所以需要next开始
        
       
    }
};

方法2:

tianjiale菜鸟名企梦
原文地址:https://www.cnblogs.com/tianjiale/p/10975345.html