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

链表相加(二)

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

链表翻转相加,结果再翻转

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        //链表反转 相加 再反转
        ListNode* newList1 = reverse(head1);
        ListNode* newList2 = reverse(head2);
        ListNode* dh = new ListNode(0),*cur = dh;
        int c = 0,num=0;
      	//有进位、任意链表还有长度
        while(newList1||newList2||c){
          	//每一位相加
            int tmp=(newList1?newList1->val:0) + (newList2?newList2->val:0)+c;
          	//处理进位
            c = tmp/10;
            num = tmp%10;
          	//将结果载入新链表
            ListNode* n = new ListNode(num);
            cur->next = n;
            cur = cur->next;
			//处理链表迭代
            newList1 = newList1==nullptr?nullptr:newList1->next;
            newList2 = newList2==nullptr?nullptr:newList2->next;
        }
      	//翻转最后结果
        return reverse(dh->next);

    }
	//迭代翻转
    ListNode* reverse(ListNode* head){
        ListNode* pre = nullptr,*cur = head,*next = cur->next;
        while(cur!=nullptr){
            cur->next = pre;
            pre = cur;
            cur = next;
            next = next->next;
        }
        return pre;
    }

};
全部评论

相关推荐

01-24 08:13
已编辑
合肥工业大学 Java
程序员牛肉:没啥问题。标准的流水线简历,但是学历好一点,所以应该是有约面的机会的。 这段时间可以考虑把自己的两个项目彻底的理一理。争取能够讲清楚每一个功能点
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务