2. Add Two Numbers——Python

題目:node

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

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

代碼:app

該題目其實就是鏈表中的數字取出來,而後相加,不過注意高位數字在後面,須要倒過來。好比題目例子中就是要:342+465=807,以後把807每一位從小到大記錄在一個鏈表裏。spa

因而,我用了最常規的辦法,不過也是解決了問題的:code

#coding:utf-8
# 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
        """
        if not l1 and not l2:return
        #取出鏈表中的數字存入數組
        arr1,arr2=[],[]       
        while l1:
            arr1.append(l1.val)    
            l1 = l1.next
        while l2:
            arr2.append(l2.val)    
            l2 = l2.next 
        #倒序
        arr1.reverse()
        arr2.reverse()
        #print (arr1,arr2)
        #組成數字
        num1,num2 = 0,0
        for i in arr1:
            num1 = num1*10+i
        for i in arr2:
            num2 = num2*10+i        
        print (num1,num2)
        #相加
        num_total = num1+num2
        print (num_total)
        #從低位到高位寫入鏈表,初始化鏈表的根節點爲0,若是相加的和爲0,直接返回
        l_res = ListNode(0)
        cursor = l_res
        if num_total == 0: return l_res
        while num_total:
            temp = num_total%10
            print (temp)
            cursor.next = ListNode(temp)
            cursor = cursor.next
            num_total = int(num_total/10)
            #print (num_total)
        return l_res.next
            
        
if __name__=='__main__':
    #建立l1和l2兩個鏈表,注意,排序好的就須要arr1和arr2中數字從小到大
    arr1 = [0,8,6,5,6,8,3,5,7]
    arr2 = [6,7,8,0,8,5,8,9,7]
    l1 = ListNode(arr1[0])
    p1 = l1
    l2 = ListNode(arr2[0])
    p2 = l2
    for i in arr1[1:]:
        p1.next = ListNode(i)
        p1 = p1.next
    for i in arr2[1:]:
        p2.next = ListNode(i)
        p2 = p2.next    
    s=Solution()
    #兩個鏈表相加
    q=s.addTwoNumbers(l1,l2)  

一些打印的輸出:blog

753865680 798580876
1552446556
6
5
5
6
4
4
2
5
5
1
相關文章
相關標籤/搜索