题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    
    ListNode* reverseList(ListNode* head) {
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while(cur) {
            ListNode* next = cur->next;
            cur->next = pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* cur1 = reverseList(head1);//翻转链表
        ListNode* cur2 = reverseList(head2);//翻转链表
        ListNode* resHead=nullptr;
        int cnt = 0;
        int x1=0,x2=0,sum=0;
        while(cur1 || cur2) { //如果两个值的加和>10,就会产生进位,这个用来存储进位
            if(cur1==nullptr) x1=0; 
            else x1=cur1->val;
            if(cur2==nullptr) x2=0; 
            else x2=cur2->val;
            sum = x1+x2+cnt;
            cnt = sum / 10;
            ListNode* tmpNode = new ListNode(sum%10);
            tmpNode->next = resHead;
            resHead = tmpNode;
            if(cur1) cur1=cur1->next;
            if(cur2) cur2=cur2->next;
        }
        // 如果cnt>0 那么就说明存在进位还得插入一个节点
        if(cnt > 0) {
            ListNode* newNode = new ListNode(cnt);
            newNode->next = resHead;
            resHead = newNode;
        }
        return resHead;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 10:05
小米集团 算法工程师 28.0k*15.0
泡沫灬一触即破:楼上那个看来是看人拿高薪,自己又不如意搁这泄愤呢是吧,看你过往评论很难不怀疑你的精神状态
点赞 评论 收藏
分享
穿件外套出门:这简历一眼太水了,前面有的没的直接删,写项目亮点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务