头插法:
每次插入节点从头节点插入
尾插法:
每次插入节点从尾节点插入
def addTwoNumbers(self, l1, l2):
"""
注意
1.初始化的是头节点,最后的结果要返回头节点的next
2.节点的插入的时候注意顺序,箭头指向哪个哪个在等号的右边
主要思想是头插法构建链表
"""
stack1,stack2,flag = [],[],0
head = ListNode(0)
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
while stack1 and stack2:
t = int(stack1.pop() + stack2.pop()+flag)
####头插法插入链表
if t < 10:
p = ListNode(t)
p.next = head.next
head.next = p
flag = 0
####保存大于10的余数
else:
a = int(t%10)
flag = int(t/10)
p = ListNode(a)
p.next = head.next
head.next = p
while stack1:
t = int(stack1.pop()) + flag
if t < 10:
p = ListNode(t)
p.next = head.next
head.next = p
flag = 0
else:
a = int(t%10)
p = ListNode(a)
p.next = head.next
head.next = p
flag = int(t/10)
while stack2:
t = int(stack2.pop()) + flag
if t < 10:
p = ListNode(t)
p.next = head.next
head.next = p
flag = 0
else:
a = int(t%10)
p = ListNode(a)
p.next = head.next
head.next = p
flag = int(t/10)
if flag != 0:
p = ListNode(flag)
p.next = head.next
head.next = p
return head.next
整理代码
def addTwoNumbers(self, l1, l2):
"""
"""
stack1, stack2, flag = [], [], 0
head = ListNode(0)
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
while stack1 and stack2:
t = int(stack1.pop() + stack2.pop() + flag)
flag = self.insert_head(t,head)
while stack1:
t = int(stack1.pop()) + flag
flag = self.insert_head(t, head)
while stack2:
t = int(stack2.pop()) + flag
flag = self.insert_head(t, head)
if flag != 0:
p = ListNode(flag)
p.next = head.next
head.next = p
return head.next
def insert_head(self,t,head):
####头插法插入链表
if t < 10:
p = ListNode(t)
p.next = head.next
head.next = p
flag = 0
####保存大于10的余数
else:
a = int(t % 10)
flag = int(t / 10)
p = ListNode(a)
p.next = head.next
head.next = p
return flag