Python编程练习.两数之和(链表版)

初学者暴力求解

数据需要在链表与List之间来回传递

# 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
        """
        a=l1.val
        b=l2.val
        ac=[a]
        bc=[b]
        result=[]
        while l1.next is not None:
            l1=l1.next
            ac.append(l1.val)
        while l2.next is not None:
            l2=l2.next
            bc.append(l2.val)
        print(ac)
        print(bc)
        if len(ac)-len(bc)>=0:
            o=[0 for i in range(len(ac)-len(bc))]
            bc=bc+o+[0]
            ac=ac+[0]
            judge=False
            for j in range(len(ac)):
                w=ac[j]+bc[j]
                if not judge:
                    if w>=10:
                        p=w-10
                        result.append(p)
                        judge=True
                        continue
                    result.append(w)
                    judge=False
                if judge:
                    w+=1
                    if w>=10:
                        judge=True
                        p=w-10
                        result.append(p)
                        continue
                    judge=False
                    result.append(w)  
        else:
            o=[0 for i in range(len(bc)-len(ac))]
            ac=ac+o+[0]
            bc=bc+[0]
            judge=False
            for j in range(len(ac)):
                w=ac[j]+bc[j]
                if not judge:
                    if w>=10:
                        p=w-10
                        result.append(p)
                        judge=True
                        continue
                    result.append(w)
                    judge=False
                if judge:
                    w+=1
                    if w>=10:
                        judge=True
                        p=w-10
                        result.append(p)
                        continue
                    judge=False
                    result.append(w)  
        if result[-1]==0:
            result=result[:-1]
        for i in range(len(result)):
            if i==0:
                head=ListNode(result[i])
                x=head
            else:
                p=ListNode(result[i])
                x.next=p
                x=p

        return head

代码执行时间180ms,高于38%的代码

你可能感兴趣的:(python)