zoukankan      html  css  js  c++  java
  • LeetCode 2:Add Two Numbers

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           ListNode cur1 = l1;
           ListNode cur2 = l2;
           ListNode head = null;
           ListNode cur = null;
           int sum = 0;
           while (cur1 != null || cur2 != null) {
               if (cur1 != null) {
                   sum += cur1.val;
                   cur1 = cur1.next;
               }
               if (cur2 != null) {
                   sum += cur2.val;
                   cur2 = cur2.next;
               }
               if (head == null) {
                   head = new ListNode(sum % 10);
                   cur = head;
               } else {
                   cur.next = new ListNode(sum % 10);
                   cur = cur.next;
               }
               sum /= 10;
           }
           if (sum == 1)
               cur.next = new ListNode(1);
           return head;
        }
    }

    中间那部分处理head是否为null的情况比较麻烦,可以采用一个 dummy node 简化

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           ListNode cur1 = l1;
           ListNode cur2 = l2;
           ListNode head = new ListNode(0);
           ListNode cur = head;
           int sum = 0;
           while (cur1 != null || cur2 != null) {
               if (cur1 != null) {
                   sum += cur1.val;
                   cur1 = cur1.next;
               }
               if (cur2 != null) {
                   sum += cur2.val;
                   cur2 = cur2.next;
               }
               cur.next = new ListNode(sum % 10);
               cur = cur.next;
               sum /= 10;
           }
           if (sum == 1)
               cur.next = new ListNode(1);
           return head.next;
        }
    }

    2015-10-15

  • 相关阅读:
    NET 获取实例所表示的日期是星期几
    NET npoi 保存文件
    快速排序
    JAVA poi 合并单元格
    JAVA poi 帮助类
    JAVA 字符串编码转换
    NET npoi 合并单元值处理
    NET npoi帮助类
    Task的暂停,继续,取消
    .net ref与out之间区别
  • 原文地址:https://www.cnblogs.com/whuyt/p/4883846.html
Copyright © 2011-2022 走看看