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 }

 

你可能感兴趣的:(LeetCode)