code2 Add Two Numbers:
Add to List
Share
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解答:
- 复现链表
- 开始解题。寻找临界点与边界点:
临界条件:元素加和,取10的 余商 商进位到下一位(如果有商>1的话),本位留 余。
边界条件:位数不等时,默认少的一方为0或者不取值;进位;
复现链表代码(包含各中方法以及测试样例):
#
#需要搞清楚,node对象属性类的关系!!!!!!!!!!!!!!??????????
#
class Node:
def __init__(self,value=None,next=None):
self.value = value ###value connects to definite value
self.next = next ### next connects to a node, and node is class(object)
class LinkedList:
def __init__(self):
self.head = None #important. head is node not attribute.
self.tail = None
self.length = 0
def isEmpty(self):
#print(self.head)
#print(self.head.value)
return self.head is None
def print_all(self):
if self.isEmpty():
return
else:
current_node = self.head
while current_node is not None:
print(current_node.value,type(current_node.next))
current_node = current_node.next
###test for isEmpty() and print_all()
'''a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.head.next = n2
a.head.next.next = n3
print(a.isEmpty())
a.print_all()'''
###
def print_index(self,ind):
current_node =self.head
count = 0
while current_node != None:
if count == ind:
print(current_node.value)
return current_node.value
count +=1
current_node = current_node.next
print('index is over the length.')
###test for print_index()
'''a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.head.next = n2
a.head.next.next = n3
a.print_all()
print('###')
a.print_index(3)'''
###
def add_before_head(self,new_head):
new_node = Node(new_head,None)
new_node.next = self.head
self.head = new_node
def add_after_tail(self,new_tail):
new_node = Node(new_tail,None)
if self.isEmpty():
self.head = new_node
else:
current_node = self.head
while current_node.next != None:
current_node = current_node.next
current_node.next = new_node
####test for add_before_head() and add_after_tail()
'''a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.add_before_head('wzy')
a.add_after_tail([1,3,5])
a.print_all()'''
###
def search_whether_exist(self,target):
answer = False
if self.isEmpty():
print('it is empty.')
return answer
else:
current_node = self.head
while current_node != None:
if current_node.value == target:
answer = True
return answer
current_node = current_node.next
return answer
###test for search_whether_exist()
'''a= LinkedList()
#a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.add_before_head('wzy')
a.add_after_tail([1,3,5])
a.print_all()
print(a.search_whether_exist([1,3,5]))'''
###
def search_index(self,ind):
count = 0
current_node = self.head
while current_node != None:
if count == ind:
return current_node.value
current_node = current_node.next
count +=1
return 'index is over the length.'
###test for search_index()
'''a= LinkedList()
#a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
#a.add_before_head('wzy')
#a.add_after_tail([1,3,5])
a.print_all()
print(a.search_index(1))'''
###
def remove_index(self,ind): #if index is too big, there is nothing happening
if ind == 0:
self.head = self.head.next
return self.print_all()
else:
count = 1
current_node = self.head
while current_node != None and current_node.next !=None:
#if the next is None, we can not get its next attribute
#and our target is next, if it is None, we do nothing.
if count == ind:
current_node.next = current_node.next.next
return self.print_all()
current_node = current_node.next
count+=1
print('nothing happens')
return self.print_all()
###test for remove_index()
'''a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.add_before_head('wzy')
a.add_after_tail([1,3,5])
a.print_all()
print('###')
a.remove_index(0)'''
###
def remove_target(self,target):
if target == self.head.value:
self.head = self.head.next
return self.print_all()
else:
current_node = self.head
while current_node != None and current_node.next != None:
# if the next is None, we can not get its next attribute
# and our target is next, if it is None, we do nothing.
#print('???',current_node.next.value,target)
if current_node.next.value == target:
current_node.next = current_node.next.next
return self.print_all()
current_node = current_node.next
print('nothing happens')
return self.print_all()
###test for remove_target()
'''a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.add_before_head('wzy')
a.add_after_tail([1,3,5])
a.print_all()
print('###')
a.remove_target([1,3,5])'''
###
def add_byindex(self,ind,value):
if ind == 0:
self.add_before_head(value)
return self.print_all()
else:
count = 1
current_node = self.head
while current_node != None :
# when the next is None,we just need to add it to new_node and add new_node to current_node
if count == ind:
new_node = Node(value)
new_node.next = current_node.next
current_node.next = new_node
return self.print_all()
count +=1
current_node = current_node.next
print('nothing happens')
return self.print_all()
###test for add_byindex()
'''a = LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1, 2, 3])
a.add_before_head('wzy')
a.add_after_tail([1, 3, 5])
a.print_all()
print('###')
a.add_byindex(4,'aaa')'''
###
a= LinkedList()
a.head = Node(6)
n2 = Node('xxy')
n3 = Node([1,2,3])
a.head.next = n2
a.head.next.next = n3
print(a.isEmpty())
a.print_all()
但是题中考查有所不同,参照输入输出可以知道,返回一个 class ListNode 的对象才行。
解答:
- 利用ListNode类新建一个节点(val为0),head指向这个对象,同时需要预留一个res作为最后的结果返回(因为head在链表内变动,指向会出现变化,但是最开始预留的res一直指向链表的第一个元素)
- 进入while循环:判断 l1 l2 如果不同时为0,则取其val的和(如果有一个为0,直接取另一个)。但是第二位的val需要前一位的carry值,所以在while默认一个carry=0
- 得到sum以后,得到val = mod和carry = // 的结果,直接通过ListNode(carry)赋值给head.next(这里需要判断是否最后一位还要做进位,如果后面没有元素了,那么0进位不进,如果1进位就进。)(别人的方法也有不一样的过程,理解即可。)
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
#print(head)
res = head
carry = 0
while l1 is not None or l2 is not None:
if l1 is not None and l2 is not None:
sum = l1.val + l2.val + carry
print(l1,l2)
print(sum)
l1 = l1.next
l2 = l2.next
#carry = (l1.val + l2.val)//10
elif l1 is not None and l2 is None:
sum = l1.val + carry
l1 = l1.next
#value = (l1.val + l2.val)%10
#carry = (l1.val + l2.val)//10
elif l1 is None and l2 is not None:
sum = l2.val + carry
l2 = l2.next
#value = (l1.val + l2.val)%10
#carry = (l1.val + l2.val)//10
carry = sum//10
value = sum%10
print(value)
#print(head)
head.val = value
print(head,'###')
if l1 is not None or l2 is not None:
head.next = ListNode(carry)
head = head.next
#head.val = 0
print(head)
return res
PS:
leetcode中自带的链表输入输出,可以理解为它将输入的数组变为了链表,将return值返回了数组。
关于链表的使用非常重要,任需加强!