LeetCode 2 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

题目比较简单,需要注意边界情况的处理和链表指针的使用,代码如下:

 1 class ListNode {
 2     int val;
 3     ListNode next;
 4 
 5     ListNode(int x) {
 6         val = x;
 7         next = null;
 8     }
 9 }
10 
11 public class AddTwoNumbers2 {
12     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
13         ListNode head = null;
14         ListNode ll1 = l1;
15         ListNode ll2 = l2;
16         int res = 0;
17         ListNode cur = null;
18         while (true) {
19             int curval = 0;
20             curval += res;
21             if (ll1 == null && ll2 == null) {
22                 if (curval != 0) {
23                     cur.next = new ListNode(curval);
24                 }
25                 break;
26             }
27             if (ll1 != null) {
28                 curval += ll1.val;
29                 ll1 = ll1.next;
30             }
31             if (ll2 != null) {
32                 curval += ll2.val;
33                 ll2 = ll2.next;
34             }
35             if (curval >= 10) {
36                 res = 1;
37                 curval -= 10;
38             } else {
39                 res = 0;
40             }
41             if (cur == null) {
42                 head = cur = new ListNode(curval);
43             } else {
44                 cur.next = new ListNode(curval);
45                 cur = cur.next;
46             }
47         }
48         return head;
49     }
50 }

参考源码:https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/L2_AddTwoNumbers.java

原文地址:https://www.cnblogs.com/pkufork/p/ds_leetcode_2.html