/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        var list = new List<ListNode>();
            var temp1 = l1;
            var temp2 = l2;
            var step = 0;
            while (l1 != null || l2 != null)
            {
                var v1 = 0;
                var v2 = 0;
                if (l1 == null)
                {
                    l1 = new ListNode(0);
                }
                v1 = l1.val;
                l1 = l1.next;

                if (l2 == null)
                {
                    l2 = new ListNode(0);
                }
                v2 = l2.val;
                l2 = l2.next;

                var cur = v1 + v2 + step;
                var result = 0;
                if (cur >= 10)
                {
                    step = 1;
                    result = cur % 10;
                }
                else
                {
                    step = 0;
                    result = cur;
                }
                list.Add(new ListNode(result));
            }
            if (step == 1)
            {
                list.Add(new ListNode(1));
            }

            for (int i = 0; i < list.Count - 1; i++)
            {
                list[i].next = list[i + 1];
            }
            var head = list[0];
            return head;
    }
}

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

补充python实现:

 1 class Solution:
 2     def addTwoNumbers(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
 3         headnode = ListNode(0)
 4         temp = headnode
 5         carry = 0
 6         while  l1!=None or l2!=None:
 7             if l1==None:
 8                 l1 = ListNode(0)
 9             if l2==None:
10                 l2 = ListNode(0)
11             cur = l1.val + l2.val + carry
12             if cur // 10 > 0:
13                 carry = 1
14             else:
15                 carry = 0
16             cur = cur % 10
17             temp.next = ListNode(cur) 
18             temp = temp.next
19             l1 = l1.next
20             l2 = l2.next
21         if carry > 0:
22             temp.next = ListNode(carry)
23         return headnode.next

 

posted on 2017-05-03 16:57  Sempron2800+  阅读(593)  评论(0编辑  收藏  举报