leetcode2. Add Two Numbers

leetcode2. Add Two Numbers

题意:

给定两个非空的链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加两个数字并将其作为链表返回。

你可以假设两个数字不包含任何前导零,除了数字0本身。

思路:

O(n)遍历两个链表,两个节点和一个carry(用于记录前面相加大于10的变量)相加放入res链表中,记录除数和余数直到遍历结束。

ac代码:

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int up=0;
        ListNode node = ListNode(0);
        ListNode* head = &node;
        while(l1||l2||up)
        {
            int temp = (l1?l1->val:0)+(l2?l2->val:0)+up;
            head->next = new ListNode(temp%10);
            up = temp/10;
            head = head->next;
            l1 = l1?l1->next:l1;
            l2 = l2?l2->next:l2;
        }
        return node.next;
    }   
};

python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        res = []
        while l1 or l2 or carry:
            a = b =0
            if l1:
                a = l1.val
                l1 = l1.next
            if l2:
                b = l2.val
                l2 = l2.next
            temp = a + b + carry
            res.append(temp%10)
            carry = temp // 10
        return res
            

tip:

循环体中使用的局部变量,每次循环都是使用同一块内存,所以每次都是同一个地址。

posted on 2017-07-09 22:14  炮二平五  阅读(512)  评论(0编辑  收藏  举报

导航