No.002: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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

官方难度:

Medium

 

翻译:

现有2个链表结构,每个节点存储非负整数,每个结点的数字都是个位数且倒序排列,将这2个链表代表的数字相加。

 

例子:

链表一:2 -> 4 -> 3

链表二:5 -> 6 -> 4

输出链表:7 -> 0 -> 8

 

额外例子:

链表一:1 -> 5  

链表二:8 -> 5  

输出链表:9 -> 0 -> 1

 

  1. 结点定义已经给了,是单向链表的结点定义:
    1     private static class ListNode {
    2         int val;
    3         ListNode next;
    4 
    5         ListNode(int x) {
    6             val = x;
    7         }
    8     }
    ListNode
  2. 最初题目给的例子,其实题意并不是特别清晰,一开始我的理解其实是存在问题的。其实题目的要求是(以额外例子为例):1+8=9,放入输出链表的第一个结点;5+5=10,放入第二个结点,产生进位;1放入第三个结点。
  3. 分析一下题目的要求,返回的要求是第一个结点,那么就需要2个指针,一个用来操作,一直next,一个始终指向第一个结点,用于return。
  4. 需要一个进位的标志位carry,而且没有必要用boolean型的,用int型的更好,可以初始值赋值0,下一次的carry=(num1+num2+carry)/10。
  5. 因为可能出现2个输入链表长短不一致的情况,当前结点为null时,赋值0就行了。
  6. 引入头结点的概念,因为初始的结点需要赋值,如果初始化为第一个结点的时候,会把大部分循环里的事情先拉出来做一遍,这样代码就会显得很繁琐,引入头结点可以避免这种情况,return的时候记得head.next。
  7. 循环退出条件是两个链表当前结点全是null,在退出循环之后需要判断进位的标志位carry,因为可能会多产出一位。
  8. 对方法进行入参检查是一个好习惯,但是本方法即使没有入参检查(输入2个null),也不会出错,只会返回null,那就不必写了。

 

解题代码:

 1     public static ListNode addTwoNumbers(ListNode l1, ListNode l2)     {
 2         // 头结点
 3         ListNode head = new ListNode(0), operNode = head;
 4         // 进位标志
 5         int carry = 0;
 6         while (l1 != null || l2 != null) {
 7             int num1 = l1 == null ? 0 : l1.val;
 8             int num2 = l2 == null ? 0 : l2.val;
 9             int sum = num1 + num2 + carry;
10             operNode.next = new ListNode(sum % 10);
11             carry = sum / 10;
12             operNode = operNode.next;
13             l1 = l1 == null ? null : l1.next;
14             l2 = l2 == null ? null : l2.next;
15         }
16         // 最后一次相加之后判断标志位
17         if (carry == 1) {
18             operNode.next = new ListNode(1);
19         }
20         return head.next;
21     }
addTwoNumbers

 

备注:

    1.  鉴于之后有比较多的链表结构的问题,不妨自己实现一下链表。

 

相关链接:

https://leetcode.com/problems/add-two-numbers/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q002.java

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/structure/SinglyLinkedList.java

 

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

 

posted @ 2016-09-22 21:00  Gerrard_Feng  阅读(349)  评论(0)    收藏  举报