add:
返回的是一个新的链表根节点
add2:
返回的是多项式1的链表的根节点
class Node(object):
"""docstring for Node"""
def __init__(self,coef=None,exp=None,next=None):
self.coef = coef
self.exp = exp
self.next = next
class Solution(object):
"""docstring for Solution"""
def add(self,poly1,poly2):
poly1 = poly1.next
poly2 = poly2.next
root = Node()
poly3 = root # 这样poly3的每次链接指向才是对于root的
while poly1 and poly2:
if poly1.exp == poly2.exp:
coef = poly1.coef+poly2.coef
if coef !=0:
node = Node(coef,poly1.exp)
poly3.next = node
poly3 = poly3.next
poly1 = poly1.next
poly2 = poly2.next
continue
if poly1.exp > poly2.exp:
node = Node(poly1.coef,poly1.exp)
poly3.next = node
poly1 = poly1.next
else:
node = Node(poly2.coef,poly2.exp)
poly3.next = node
poly2 = poly2.next
poly3 = poly3.next
temp = poly1
if poly1 is None: temp = poly2
while temp:
node = Node(temp.coef,temp.exp)
poly3.next = node
poly3 = poly3.next
temp = temp.next
return root
def add2(self,poly1,poly2):
root = poly1
# 第一次写成了root=tail=poly1,这样相当于root和tail都指向poly1
# 这样的问题就是没法对root进行链接操作
tail = root
poly1 = poly1.next
poly2 = poly2.next
while poly1 and poly2:
if poly1.exp == poly2.exp:
sum = poly1.coef+poly2.coef
if sum !=0:
poly1.coef = sum
tail.next = poly1
tail = tail.next
poly1 = poly1.next
poly2 = poly2.next
continue
else:
poly1 = poly1.next
poly2 = poly2.next
continue
if poly1.exp > poly2.exp:
tail.next = poly1
tail = tail.next
poly1 = poly1.next
continue
if poly1.exp < poly2.exp:
tail.next = poly2
tail = tail.next
poly2 = poly2.next
tail.next = poly1
continue
if poly2: tail.next = poly2
return root
def create_linklist(n):
root = Node()
tail = root
for i in range(n,n-5,-1):
node = Node(i,i)
tail.next = node
tail = node
return root
def test_add_1and2():
a = create_linklist(5)
b = create_linklist(8)
sol = Solution()
res = sol.add2(a,b)
res = res.next
while res:
print(res.coef,res.exp)
res = res.next