zoukankan      html  css  js  c++  java
  • lincode167

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;      
     *     }
     * }
     */
    public class Solution {
        /**
         * @param l1: the first list
         * @param l2: the second list
         * @return: the sum list of l1 and l2 
         */
        public ListNode addLists(ListNode l1, ListNode l2) {
            // write your code here
    
            int digit1 = l1.val;
            int digit2 = l2.val;
            int digitS = (digit1 + digit2) % 10;
            int c = (digit1 + digit2) / 10;
            l1 = l1.next;
            l2 = l2.next;
    
            ListNode sum = new ListNode(digitS);
            ListNode head = sum;
    
            while (!(l1 == null && l2 == null && c == 0)){
                digit1 = l1 == null ? 0 : l1.val;
                digit2 = l2 == null ? 0 : l2.val;
                digitS = (digit1 + digit2 + c) % 10;
                c = (digit1 + digit2 + c) / 10;
                l1 = l1 == null ? l1 : l1.next;
                l2 = l2 == null ? l2 : l2.next;
                sum.next = new ListNode(digitS);
                sum = sum.next;
            }
    
            return head;
        }
    }

    1. 小心处理l1和l2其中有一个先null了的情况,可以digit1 = l1 == null ? 0 : l1.val;
    2. 还有小心l1后移的情况,如果l1已经是null了,那就不能后移了,所以要l1 = l1 == null ? l1 : l1.next;
    3. 小心后面每次加的时候要多加个c;

  • 相关阅读:
    [python] defaultdict
    [VM workstation]VM workstation 中的虚拟机连不上网络
    [Docker] docker 基础学习笔记1(共6篇)
    [python] import curses
    servlet 产生随机验证码
    JSTL标签库 sql标签
    JSTLLearning
    Ajax实现联想(建议)功能
    HDU 1241
    Servlet实现文件上传
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7498377.html
Copyright © 2011-2022 走看看