兩數相加(Leetcode)
# 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
"""
len1 = 0
len2 = 0
head1 = l1#留下頭結點
head2 = l2
lis = ListNode(0)
while(head1!=None):#求一下長度,雖然也可以用while (l1!=None):來解決,但我還是求了
head1 = head1.next
len1 += 1
while(head2!=None):
head2 = head2.next
len2 += 1
head1 = l1
head2 = l2
headlis = lis
if(len1>=len2):#沒啥好說的。。下面都都是簡單的程式碼。。
for i in range(len2):
headlis.val = head1.val + head2.val + headlis.val
head1 = head1.next
head2 = head2.next
if(len1!=len2):
if(headlis.val>=10):
headlis.val = headlis.val - 10
headlis.next = ListNode(1)
headlis = headlis.next
else:
headlis.next = ListNode(0)
headlis = headlis.next
if(len1==len2):
if(headlis.val>=10):
headlis.val = headlis.val - 10
headlis.next = ListNode(1)
headlis = headlis.next
else:
if(i<len2-1):
headlis.next = ListNode(0)
headlis = headlis.next
for i in range(len2,len1):
headlis.val = head1.val + headlis.val
head1 = head1.next
if(headlis.val>=10):
headlis.val = headlis.val - 10
headlis.next = ListNode(1)
headlis = headlis.next
elif(i<len1-1):
headlis.next = ListNode(0)
headlis = headlis.next
if(len1<len2):
for i in range(len1):
headlis.val = head1.val + head2.val + headlis.val
head1 = head1.next
head2 = head2.next
if(headlis.val>=10):
headlis.val = headlis.val - 10
headlis.next = ListNode(1)
headlis = headlis.next
else:
headlis.next = ListNode(0)
headlis = headlis.next
for i in range(len1,len2):
headlis.val = head2.val + headlis.val
head2 = head2.next
if(headlis.val>=10):
headlis.val = headlis.val - 10
headlis.next = ListNode(1)
headlis = headlis.next
elif(i<len2-1):
headlis.next = ListNode(0)
headlis = headlis.next
return lis
'''
這裡比較難受的就是,我以為它傳給我的是一個帶有表頭的連結串列(即第一個節點值為空,指標往下指),然鵝並不是。
後來我發現,在LeetCode裡面可以用print輸出。。我太tm開心了。。
最後膜拜了一下大佬的程式碼
rem = 0
dummy = ListNode(0)
p = dummy
while l1 or l2 or rem:
s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + rem
rem = s/10
p.next = ListNode(s%10)
p = p.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next
'''