两个链表相加(Python)
两个链表生成相加链表
http://www.nowcoder.com/questionTerminal/c56f6c70fb3f4849bc56e33ff2a50b6b
自己一开始写的是链表值转到字符串,运算完得到新的字符串再分割组成链表,一直超时。
def f(head): s = '' while head: s += str(head.val) head = head.next return s class Solution: def addInList(self , head1 , head2 ): s = list(str(eval(f(head1) + '+' + f(head2)))) head = ListNode(int(s.pop(0))) cur, nex = head, head while s: nex = ListNode(int(s.pop(0))) cur.next = nex cur = cur.next return head
绝望,只能借鉴一下排行榜上的大佬,把他的代码改简单了一点。
ps:讲解一下29行
- 还没加完更短的一条(num2)时,需要加 num2[i].val;
- 当 num2 用完若再加就 index out 了,但这个时候 carry(进位)可能还有,所以加法还要进行,但 num2 没了就加 0
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head1 ListNode类 # @param head2 ListNode类 # @return ListNode类 # def f(head): '''把节点放入列表中,并反转''' num = [] while head: num.append(head) head = head.next return num[::-1] class Solution: def addInList(self , head1 , head2 ): num1, num2, carry = f(head1), f(head2), 0 if len(num1) < len(num2): num1, num2 = num2, num1 for i in range(len(num1)): if i < len(num2) or carry: summation = num1[i].val + (num2[i].val if i < len(num2) else 0) + carry carry, num = divmod(summation, 10) num1[i].val = num else: break if carry: carryhead = ListNode(carry) carryhead.next = num1[-1] return carryhead return num1[-1]