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

链表相加(二)

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;
    }
};

全部评论

相关推荐

10-22 15:25
门头沟学院 C++
种花网友小松:求求你别发了,我几乎都快嫉妒得疯了,倒在床上蒙住被子就开始抱着枕头尖叫流泪,嘴里一边喊着卧槽卧槽,一边又忍着,我边发边哭,打字的手都是抖的,后来我的手抖得越来越厉害,从心头涌起的思想、情怀和梦想,这份歆羡和悔恨交织在一起,我的笑还挂在脸上,可是眼泪一下子就掉下来了。求你了别发了,我生活再难再穷我都不会觉得难过,只有你们发这种东西的时候,我的心里像被刀割一样的痛,打着字泪水就忍不住的往下流。
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务