• 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

  • 相关阅读:
    [NOI2003]文本编辑器
    [TyvjP1413]费用流模板裸题
    POJ 3255 dijkstra次短路
    [TyvjP1474]二维线段树区间更新+查询
    [转]二分图的必须边
    匈牙利算法代码及理解
    jloi2013一些想法
    uva11987 并查集小技巧
    【水】tyvj1523 平面几何入门
    Tyvj1462 细节凸包
  • 原文地址:https://www.cnblogs.com/whuyt/p/4883846.html
Copyright © 2020-2023  润新知