题解 | 链表相加(二)

链表相加(二)

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* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        auto current1 = head1;
        auto current2 = head2;
        auto newHead1 = reverseListNode(current1);
        auto newHead2 = reverseListNode(current2);
        current1 = newHead1;
        current2 = newHead2;
        ListNode* result = nullptr;
        int add = 0;
        while (current1 || current2) {
            int num1 = 0;
            int num2 = 0;
            if(current1){
                num1 = current1->val;
                auto temp1 = current1->next;
                current1 = temp1;
            }  
            if(current2){
                num2 = current2->val;
                auto temp2 = current2->next;
                current2 = temp2;
            }  
            int sum =num1+num2+add;
            if(sum > 9){
                result = insertNode(result, sum - 10);
                add = 1;
            }
            else{
                result = insertNode(result, sum);
                add = 0;
            }                       
        }
        if(add > 0)
            result = insertNode(result, 1);
        return result;
    }

    ListNode* insertNode(ListNode* head, int value){
        auto newNode = new ListNode(value);
        newNode->next = head;
        head = newNode;
        return head;
    }

    ListNode* reverseListNode(ListNode* head){
        ListNode* newHead = nullptr;
        auto current = head;
        while (current) {
            auto temp = current->next;
            current->next = newHead;
            newHead = current;
            current = temp;
        }
        return newHead;
    }
};

个人编程牛客刷题编程题目分享

全部评论

相关推荐

点赞 评论 收藏
分享
Clavoss:一眼AI,死亏
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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