Add Two Numbers 兩個連結串列相加 python
阿新 • • 發佈:2018-11-10
描述:
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