• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

这道题挺常见的,关键是要设计出好的程序结构,有一些技巧,比如建立一个假的前置节点ListNode prenode = new ListNode(-1); 比如循环条件设置为 while (l1 != null || l2 != null || carry != 0),我第一遍写的时候就是没有想到用“或”来写循环结构,导致下面有好多种子情况需要一一讨论,使得程序变得非常繁复,不似这样写架构清晰,思路明确。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
14         if (l1 == null && l2 != null) return l2;
15         if (l1 != null && l2 == null) return l1;
16         if (l1 == null && l2 == null) return null;
17         
18         ListNode prenode = new ListNode(-1);
19         ListNode end = prenode;
20         int carry = 0;
21         int current = 0;
22         while (l1 != null || l2 != null || carry != 0) {
23             current = 0;
24             if (l1 != null) {
25                 current += l1.val;
26                 l1 = l1.next;
27             }
28             if (l2 != null) {
29                 current += l2.val;
30                 l2 = l2.next;
31             }
32             if (carry != 0) {
33                 current += carry;
34             }
35             end.next = new ListNode(current % 10);
36             carry = current / 10;
37             end = end.next;
38         }
39         return prenode.next;
40     }
41 }

 

posted @ 2014-06-06 23:56  neverlandly  阅读(249)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3