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

链表相加(二)

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

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* head1Reversed = reverse(head1);
        ListNode* head2Reversed = reverse(head2);
        int jinwei = 0;
        ListNode* res = nullptr;
        while(jinwei || head1Reversed || head2Reversed) {
            int nodeVal1 = head1Reversed?head1Reversed->val:0;
            int nodeVal2 = head2Reversed?head2Reversed->val:0;
            jinwei += (nodeVal1 + nodeVal2);
            ListNode* node = new ListNode(jinwei%10);
            node->next = res;
            res=node;
            jinwei = jinwei/10;
            if(head1Reversed) {
                head1Reversed = head1Reversed->next;
            }
            if(head2Reversed) {
                head2Reversed = head2Reversed->next;
            }
        }
        return res;
    }
    
    ListNode* reverse(ListNode* head) {
        ListNode* res = new ListNode(-1);
        while(head) {
            ListNode* temp = head->next;
            head->next=res->next;
            res->next=head;
            head = temp;
        }
        return res->next;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-20 19:57
已编辑
某大厂 golang工程师 23.0k*16.0, 2k房补,年终大概率能拿到
点赞 评论 收藏
分享
把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
三年之期已到我的offer快到碗里来:9硕都比不上9本
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务