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

链表相加(二)

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

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        // ArrayDeque<ListNode> l1 = new ArrayDeque<>();
        // ArrayDeque<ListNode> l2 = new ArrayDeque<>();
        // while(head1 != null){
        //     l1.push(head1);
        //     head1 = head1.next;
        // }
        // while(head2 != null){
        //     l2.push(head2);
        //     head2 = head2.next;
        // }
        // ListNode post = null;
        // ListNode now = null;
        // int temp = 0;
        // while(!l1.isEmpty() || !l2.isEmpty()){
        //     int a = l1.isEmpty() ? 0 : l1.pop().val;
        //     int b = l2.isEmpty() ? 0 : l2.pop().val;
        //     int max = a + b + temp;
        //     temp = max / 10;
        //     now = new ListNode(max % 10);
        //     now.next = post;
        //     post = now;
        // }
        // if(temp != 0){
        //     now = new ListNode(temp);
        //     now.next = post;
        // }
        // return now;
        ListNode rL1 = reverseList(head1);
        ListNode rL2 = reverseList(head2);
        int temp = 0;
        ListNode pre = null;
        ListNode head = null;
        ListNode now = null;
        while(rL1 != null || rL2 != null){
            int a = rL1 == null ? 0 : rL1.val;
            int b = rL2 == null ? 0 : rL2.val;
            int sum = a + b + temp;
            temp = sum / 10;
            now = new ListNode(sum % 10);
            if( rL1 != null) rL1 = rL1.next;
            if( rL2 != null) rL2 = rL2.next;
            if(head == null){
                pre = now;
                head = now;
                continue;
            }
            pre.next = now;
            pre = now;
        }
        if(temp != 0){
            now = new ListNode(temp);
            pre.next = now;
        }
        return reverseList(head);
    }
    public ListNode reverseList(ListNode head){
        ListNode dummy = null;
        while(head != null){
            ListNode next = head.next;
            head.next = dummy;
            dummy = head;
            head = next;
        }
        return dummy;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务