2、LeetCode之两数相加

给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字0之外,这两个数都不会以0开头。

在这里插入图片描述

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

转载:数据结构:链表及其C++实现

class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
    //头尾节点
        ListNode *head=nullptr,*tail=nullptr;
        int carry=0;
        //不为null就遍历
        while(l1||l2){
    
    
        	//获取当前链表节点值
            int n1=l1?l1->val:0;
            int n2=l2?l2->val:0;
            //相加
            int sum=n1+n2+carry;
            if(!head){
    
    
            	//为空创建新的头,尾节点
                head=tail=new ListNode(sum%10);
            }else{
    
    
            	//不为空值加在尾部
                tail->next=new ListNode(sum%10);
                tail=tail->next;
            }
            carry=sum/10;
            if(l1){
    
    
                l1=l1->next;
            }
            if(l2){
    
    
                l2=l2->next;
            }
            //最后不为0,就在尾部增加一个新结点
            if(carry>0)
                tail->next=new ListNode(carry);   
        }
        return head;
    }
};

优化减少代码

class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
        ListNode *dummy = new ListNode(0);  // 虚拟头节点
        ListNode *current = dummy;
        int carry = 0;

        while (l1 || l2 || carry) {
    
    
            int n1 = l1 ? l1->val : 0;
            int n2 = l2 ? l2->val : 0;
            int sum = n1 + n2 + carry;

            current->next = new ListNode(sum % 10);
            current = current->next;

            carry = sum / 10;

            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
        }

        return dummy->next;  // 返回真实的头节点,而非虚拟头节点
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52108058/article/details/134472035