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

链表相加(一)

http://www.nowcoder.com/practice/521d83306d964c1188639033eb59621d

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    public ListNode ListAdd(ListNode l1, ListNode l2) {
        // write code here
        int carryBit = 0;
        ListNode p1 = l1;
        ListNode p2 = l2;
        Queue<ListNode> queue = new LinkedList<>();
        while (null != p1 && null != p2) {
            int tmpVal = p1.val + p2.val + carryBit;
            ListNode tmpNode = new ListNode(tmpVal % 10);
            queue.add(tmpNode);
            carryBit = tmpVal / 10;
            p1 = p1.next;
            p2 = p2.next;
        }
        while (null != p1) {
            int tmpVal = p1.val + carryBit;
            ListNode tmpNode = new ListNode(tmpVal % 10);
            queue.add(tmpNode);
            carryBit = tmpVal / 10;
            p1 = p1.next;
        }
        while (null != p2) {
            int tmpVal = p2.val + carryBit;
            ListNode tmpNode = new ListNode(tmpVal % 10);
            queue.add(tmpNode);
            carryBit = tmpVal / 10;
            p2 = p2.next;
        }
        if (carryBit == 1) {
            ListNode tmpNode = new ListNode(1);
            queue.add(tmpNode);
        }
        ListNode head = queue.poll();
        ListNode node = head;
        while (!queue.isEmpty()) {
            node.next = queue.poll();
            node = node.next;
        }
        node.next = null;
        return head;
    }
}
全部评论

相关推荐

伟大的烤冷面被普调:暨大✌🏻就是强
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务