两个数组相加

2017-03-14  本文已影响45人  水瓶鱼

题目(leetcode)

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

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
          """
          node1 = l1.next
          node2 = l2.next
          increase = l1.val + l2.val
          result = ListNode(increase % 10)
          increase //= 10
          tem = result;
          while node1 is not None or node2 is not None:
              add=0
              if node1 is not None and node2 is not None:
                  add = node1.val + node2.val + increase
              elif node1 is not None:
                  add = node1.val + increase
              else:
                  add = node2.val + increase
              result.next = ListNode(add % 10)
              increase = add // 10
              if node1:
                  node1 = node1.next
              if node2:
                  node2 = node2.next
              result = result.next
          if increase>0:
              result.next=ListNode(increase)
    
          return tem

c++

  class Solution {
  public:
      ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
          int add=l1->val+l2->val;
          ListNode *head=new ListNode(add%10);
          ListNode *tem=head;
          l1=l1->next;
          l2=l2->next;
          add=add/10;
          while(l1!=NULL&&l2!=NULL){
              add=l1->val+l2->val+add;
              ListNode *tem1=new ListNode(add%10);
              add=add/10;
              tem->next=tem1;
              tem=tem1;
              l1=l1->next;
              l2=l2->next;
          }
          if(l2!=NULL){
              l1=l2;
          }
          while(l1!=NULL){
              int n=l1->val+add;
              add=n/10;
              ListNode * tem1=new ListNode(n%10);
              tem->next=tem1;
              tem=tem1;
              l1=l1->next;
          }
          if(add!=0){
              tem->next=new ListNode(add);
          }
          return head;
      }
  };
上一篇下一篇

猜你喜欢

热点阅读