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

链表相加(二)

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

一开始没看到数据要求,试着用转成数字直接相加,结果当然是不对的,因为题目给的位数非常大,因此必须一位一位的处理。

我选择了先将两个链表反转再进行相加,要记得处理进位的情况即可。

class Solution {
  public:
  	// 反转链表
    ListNode* reverse(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* cur = head;

        while (cur) {
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        head1 = reverse(head1);
        head2 = reverse(head2);

        ListNode* cur = new ListNode(-1);
        ListNode* pre = nullptr;
        bool ex = false;// 标记进位
        while (head1 || head2) {
            int sum = 0;
            if (head1) {
                sum += head1->val;
                head1 = head1->next;
            }
            if (head2) {
                sum += head2->val;
                head2 = head2->next;
            }
            cur = new ListNode((sum + ex) % 10);
            cur->next = pre;
            pre = cur;
            ex = (sum + ex) / 10;
        }
        return cur;
    }
};
全部评论

相关推荐

昨天 13:37
重庆大学 C++
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
练习生懒羊羊:开飞机把这个公司创飞吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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