版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86608665
原题
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
解法
先定义getNum函数将链表转化为整数, 然后两整数相加, 将得到的结果转化为数字列表, 构建dummy节点, 遍历列表, 每次从列表中提取第一个数字, 作为节点的下一个节点, 最后返回dummy.next
Time: O(L1) + O(L2) + O(L1+L2), L1为l1的长度, L1+L2为l1加l2的长度
Space: O(1)
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = self.getNum(l1) + self.getNum(l2)
res = [int(char) for char in list(str(res))]
# convert res to linked list
dummy = p = ListNode(0)
while res:
p.next = ListNode(res.pop(0))
p = p.next
return dummy.next
def getNum(self, node):
l = []
while node:
l.append(str(node.val))
node = node.next
return int(''.join(l))