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

两个链表生成相加链表

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


/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if(head1 == null  && head2 == null){
            return null;
        }
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        head1 = reverse(head1);
        head2 = reverse(head2);
        //开始从最右侧 个位相加了
        int addition = 0;
        ListNode head = new ListNode(-1);
        ListNode current = head;
        while(head1 != null || head2 != null){
            int a = 0, b = 0;
            if(head1 != null){
                a = head1.val;
                head1 = head1.next;
            }
            
            if(head2 != null){
                b = head2.val;
                head2 = head2.next;
            }
            int sum = a + b +addition;
            current.val = sum % 10;
            addition = sum / 10;
            ListNode next = new ListNode(-1);
            current.next =  next;
            current = next;
        }
        current.val = addition;
        head = reverse(head);
        if(head.val == 0){
            head = head.next;
        }
        return head;
    }
        private ListNode reverse(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
全部评论

相关推荐

AFBUFYGRFHJLP:直接去美帝试试看全奖phd吧
点赞 评论 收藏
分享
废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务