题解 | #两个链表生成相加链表#

两个链表生成相加链表

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

参考其他题解给出的反转链表方法的进一步优化,引入了一些边界情况的处理

public class Solution {
    public static ListNode ReverseList(ListNode pHead) {
        ListNode res = null;
        ListNode cur = pHead;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = res;
            res = cur;
            cur = temp;
        }
        return res;
    }
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        ListNode l1 = ReverseList(head1);//翻转链表l1
        ListNode l2 = ReverseList(head2);//翻转链表l2
        ListNode h1 = l1, h2 = l2, part = null, res = null;// 用于返回的链表
        int sum, carry = 0;

        while(l1 != null && l2 != null){
            sum = l1.val + l2.val + carry;//当前这一位的总和
            carry = sum / 10;//查看当前加和是否有进位
            l1.val = l2.val = sum % 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        //根据两两相加截止和进位情况计算
        if (l1 == null && l2 == null) {
            res = h2;
            part = l2;
            if (carry > 0)
                part = new ListNode(carry);
        } else {
            if (l1 == null) {
                res = h2;
                part = l2;
            } else {
                res = h1;
                part = l1;
            }
            while (carry > 0 && part != null) {
                int ssum = part.val + carry;
                part.val = ssum % 10;
                carry = ssum / 10;
                part = part.next;
            }
            if (carry > 0) {
                part = new ListNode(carry);
            }
        }
        return ReverseList(res);
    }
}
全部评论

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
伟大的烤冷面被普调:暨大✌🏻就是强
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务