描述:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverseorder and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
python 2.7.x环境,代码如下:
# coding=utf-8
class LinkNode(object): # 定义链表节点
def __init__(self, val, nextnode=None):
self.val = val
self.nextnode = nextnode
class Solution(object):
def add_two_list(self, lista=None, listb=None):
if lista is None:
return listb
if listb is None:
return lista
ret = LinkNode(0)
p = ret
cflag = 0
while lista or listb: # 直接把两个链表的长短不一考虑进来
total = cflag
if lista:
total += lista.val
lista = lista.nextnode
if listb:
total += listb.val
listb = listb.nextnode
p.nextnode = LinkNode(total % 10)
cflag = total / 10
p = p.nextnode
if cflag == 1:
p.nextnode = LinkNode(1)
return ret.nextnode
if __name__ == '__main__':
roota = LinkNode(2)
node1 = LinkNode(4)
node2 = LinkNode(3)
roota.nextnode = node1
node1.nextnode = node2
rootb = LinkNode(5)
node3 = LinkNode(6)
node4 = LinkNode(4)
rootb.nextnode = node3
node3.nextnode = node4
out = Solution().add_two_list(roota, rootb)
while out:
print out.val
out = out.nextnode