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

链表相加(二)

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

#include <iostream>

import java.util.*;

/*
 * 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) {
        if(head1 == null){
            return head2;
        }
        if(head1 == null){
            return head1;
        }
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        
        ListNode ln = new ListNode(0);
        ListNode n = ln;
        
        int f = 0;
        while(head1 != null || head2 != null){
            int sum =f;
            if(head1 != null){
                sum += head1.val;
                head1 = head1.next;
            }
            if(head2 != null){
                sum += head2.val;
                head2 = head2.next;
            }
            n.next = new ListNode(sum%10);
            n = n.next;
            
            f = sum/10;
        }
        if(f != 0){
            n.next = new ListNode(1);
        }
        return reverseList(ln.next);
    }
    public ListNode reverseList(ListNode head){
        if(head == null){
            return head;
        }
        ListNode curr = head;
        ListNode node = null;
        while (curr != null){
            ListNode temp = curr.next;
            curr.next = node;
            node = curr;
            curr = temp;
        }
        return node;
    }
}
全部评论

相关推荐

09-22 22:22
中山大学 Java
双尔:赌对了,不用经历秋招的炼狱真的太好了,羡慕了
点赞 评论 收藏
分享
牛客小菜鸡66:boss里面,招人的叫老板,找工作的叫牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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