小编从今天起要开始分享一些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
"""
#l1.val表示当前链表的值,l1.next表示链表指针指向下一个节点
#创建头节点
self.head=ListNode(0)
p=self.head
more=0
more1=0
more2=0
while(l1!=None and l2!=None):
value=l1.val+l2.val+more data=list(str(value)) if(len(data)==1):
node=ListNode(int(data[0]))
print(int(data[0]),more)
more=0
else:
node=ListNode(int(data[1]))
print(int(data[1]),more)
more=int(data[0]) p.next=node
p=p.next
l1=l1.next
l2=l2.next if(l1!=None and l2==None):
more1=more
if(l2!=None and l1==None):
more2=more while(l1!=None):
value=l1.val+more1
data=list(str(value))
#print(data)
if(len(data)==1):
node=ListNode(int(data[0]))
print(int(data[0]),more1)
more1=0
else:
node=ListNode(int(data[1]))
print(int(data[1]),more1)
more1=int(data[0])
#print(more1)
p.next=node
p=p.next
l1=l1.next
more=0
while(l2!=None):
value=l2.val+more2
data=list(str(value))
#print(data)
if(len(data)==1):
node=ListNode(int(data[0]))
more2=0
else:
node=ListNode(int(data[1]))
more2=int(data[0])
#print(more)
p.next=node
p=p.next
l2=l2.next
more=0
if(more!=0):
node=ListNode(more)
p.next=node
if(more1!=0):
node=ListNode(more1)
p.next=node
if(more2!=0):
node=ListNode(more2)
p.next=node
p=self.head
p.val=p.next.val
p.next=p.next.next
return p