add two numbers

给你两个表示两个非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加(如果有进位就把进位加到前一位)并将其作为一个链表返回。
输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8

# -*- coding:utf-8 -*-
'''输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)输出: 7 -> 0 -> 8'''
class Node(object):    
  def __init__(self,val,p=None):        
    self.data = val        
    self.next = p
  def addTwoNumbers(n1,n2):    
    result = 0    
    resultNode = None    
    while (n1 != None) or (n2 != None):       
      if n1 != None:            
        result += n1.data            
        n1 = n1.next        
      if n2 != None:            
        result += n2.data            
        n2 = n2.next        
      if resultNode == None:            
        resultNode = Node(result % 10)            
        head = resultNode        
      else:            
        resultNode.next = Node(result % 10)            
        resultNode = resultNode.next        
        result = result // 10    
    return head
if __name__ == "__main__":    
  node1 = Node(2,Node(4,Node(3)))    
  node2 = Node(5,Node(6,Node(4)))    
  node3 = addTwoNumbers(node1,node2)    
  # print node3.data    
  while node3 != None:       
    print node3.data        
    node3 = node3.next

你可能感兴趣的:(add two numbers)