第二题,没什么复杂的直接上代码好了,简单说就是首先两个链表相加,然后反向存储,最后转化成list输出

 
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Copyright (c) 2017 Xu Zhihao (Howe).  All rights reserved.

This program is free software; you can redistribute it and/or modify

"""
carray = False

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

class ListNode_handle:
    def __init__(self):
        self.cur_node = None

    def add(self, data):
        #add a new node pointed to previous node
        node = ListNode()
        node.val = data
        node.next = self.cur_node
        self.cur_node = node
        return node

    def print_ListNode(self, node):
        while node:
            print '\nnode: ', node, ' value: ', node.val, ' next: ', node.next
            node = node.next


    def _reverse(self, nodelist):
        list = []
        while nodelist:
            list.append(nodelist.val)
            nodelist = nodelist.next
        result = ListNode()
        result_handle = ListNode_handle()
        for i in list:
            result = result_handle.add(i)
        return result

    def get_list(self, nodelist):
        list = []
        while nodelist:
            list.append(nodelist.val)
            nodelist = nodelist.next
        return list


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        global carry
        carry = False
        result_handle = ListNode_handle()
        result = ListNode()
        while l1 != None or l2 != None:
            if not carry:
                if l1 != None and l2 != None:
                    l3_val = l1.val + l2.val
                elif l1 == None and l2 != None:
                    l3_val = l2.val
                elif l1 != None and l2 == None:
                    l3_val = l1.val
                else:
                    pass
            else:
                if l1 != None and l2 != None:
                    l3_val = l1.val + l2.val + 1
                elif l1 == None and l2 != None:
                    l3_val = l2.val + 1
                elif l1 != None and l2 == None:
                    l3_val = l1.val + 1
                else :
                    pass
                carry = False
            if l3_val < 10:
                result = result_handle.add(l3_val)
            else:
                result = result_handle.add(l3_val%10)
                carry = True
            try:
                l1 = l1.next
            except:
                pass
            try:
                l2 = l2.next
            except:
                pass
        result = result_handle._reverse(result)
        result_list = []
        result_list = result_handle.get_list(result)
        if carry:
            result_list.append(1)
            result = result_handle.add(1)
            result = result_handle._reverse(result)
        result_handle.print_ListNode(result)
        return result_list

if __name__ == "__main__":
    # creat 2 linked lists
    ListNode_1 = ListNode_handle()
    l1 = ListNode()
    l1_list = [1,8]
    for i in l1_list:
        l1 = ListNode_1.add(i)

    ListNode_2 = ListNode_handle()
    l2 = ListNode()
    l2_list = [9]
    for i in l2_list:
        l2 = ListNode_2.add(i)
    #reverse 2 linked lists
    l1 = ListNode_1._reverse(l1)
    l2 = ListNode_2._reverse(l2)

    #get result
    result = Solution().addTwoNumbers(l1, l2)
    print result


首先设置进位:

carray = False

然后设置链表格式:
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self):
        self.val = None
        self.next = None

然后再设置添加链表功能:
    def add(self, data):
        #add a new node pointed to previous node
        node = ListNode()
        node.val = data
        node.next = self.cur_node
        self.cur_node = node
        return node

设置反向:
    def _reverse(self, nodelist):
        list = []
        while nodelist:
            list.append(nodelist.val)
            nodelist = nodelist.next
        result = ListNode()
        result_handle = ListNode_handle()
        for i in list:
            result = result_handle.add(i)
        return result

输出list
    def get_list(self, nodelist):
        list = []
        while nodelist:
            list.append(nodelist.val)
            nodelist = nodelist.next
        return list

两个链表相加的结果函数:

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        global carry
        carry = False
        result_handle = ListNode_handle()
        result = ListNode()
        while l1 != None or l2 != None:
            if not carry:
                if l1 != None and l2 != None:
                    l3_val = l1.val + l2.val
                elif l1 == None and l2 != None:
                    l3_val = l2.val
                elif l1 != None and l2 == None:
                    l3_val = l1.val
                else:
                    pass
            else:
                if l1 != None and l2 != None:
                    l3_val = l1.val + l2.val + 1
                elif l1 == None and l2 != None:
                    l3_val = l2.val + 1
                elif l1 != None and l2 == None:
                    l3_val = l1.val + 1
                else :
                    pass
                carry = False
            if l3_val < 10:
                result = result_handle.add(l3_val)
            else:
                result = result_handle.add(l3_val%10)
                carry = True
            try:
                l1 = l1.next
            except:
                pass
            try:
                l2 = l2.next
            except:
                pass
        result = result_handle._reverse(result)
        result_list = []
        result_list = result_handle.get_list(result)
        if carry:
            result_list.append(1)
            result = result_handle.add(1)
            result = result_handle._reverse(result)
        result_handle.print_ListNode(result)
        return result_list


官网上的解:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        carry = 0
        root = n = ListNode(0)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            n.next = ListNode(val)
            n = n.next
        return root.next

分析:

这里他默认了l1,l2是链表了,所以我之前建立链表的操作比较多余。

然后算法上,他用了

divmod
这个函数的功能是整除,返回值为(进位,余数),这也比我单独设置carry好

整体思路是:

先定义了root 和 n同时候一个指向None的值为0的ListNode,root不变

然后遍历l1,l2,

如过l1有值则取出l1中的值v1,然后将l1指向下一个

如过l2有值则取出l2中的值v2,然后将l2指向下一个

接着计算(值v1+值v2+进位)的求和之后对10求余数,得到新的进位和余数

再接着,将n指向新的余数,root保持不变

依次循环

返回root的所指向的下一位

eg:(2 -> 4 -> 3) + (5 -> 6 -> 4)

他的结果是:7 -> 0 -> 8

但是root的值为0 -> 7 -> 0 -> 8


GitHub: https://github.com/DinnerHowe/LeetCode.git


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐