LeetCode: Add two numbers

一次过, 无难度, dfs无压力

 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 class Solution {

10 public:

11     ListNode* dfs(ListNode *l1, ListNode *l2, int carry) {

12         if (!l1 && !l2) {

13             if (!carry) return NULL;

14             else {

15                 ListNode* tmp = new ListNode(carry);

16                 return tmp;

17             }

18         }

19         if (!l1) {

20             int sum = l2->val + carry;

21             ListNode* tmp = new ListNode(sum%10);

22             carry = sum/10;

23             tmp->next = dfs(l1, l2->next, carry);

24             return tmp;

25         }

26         if (!l2) {

27             int sum = l1->val + carry;

28             ListNode* tmp = new ListNode(sum%10);

29             carry = sum/10;

30             tmp->next = dfs(l1->next, l2, carry);

31             return tmp;

32         }

33         if (l1 && l2) {

34             int sum = l1->val + l2->val + carry;

35             ListNode* tmp = new ListNode(sum%10);

36             carry = sum/10;

37             tmp->next = dfs(l1->next, l2->next, carry);

38             return tmp;

39         }

40     }

41     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

42         // Start typing your C/C++ solution below

43         // DO NOT write int main() function

44         int carry = 0;

45         ListNode *ret = dfs(l1, l2, carry);

46         return ret;

47     }

48 };

 C#版,C#无指针

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     public int val;

 5  *     public ListNode next;

 6  *     public ListNode(int x) { val = x; }

 7  * }

 8  */

 9 public class Solution {

10     public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {

11         ListNode ans = null;

12         ListNode ansHead = null;

13         int c = 0;

14         while (l1 != null || l2 != null) {

15             int val = 0;

16             if (l1 != null) val += l1.val;

17             if (l2 != null) val += l2.val;

18             val += c;

19             c = val / 10;

20             if (ans == null) {

21                 ans = new ListNode(val % 10);

22                 ansHead = ans;

23             }

24             else {

25                 ans.next = new ListNode(val % 10);

26                 ans = ans.next;

27             }

28             if (l1 != null) l1 = l1.next;

29             if (l2 != null) l2 = l2.next;

30         }

31         if (c != 0) ans.next = new ListNode(c);

32         return ansHead;

33     }

34 }
View Code

 

你可能感兴趣的:(LeetCode)