1. 程式人生 > 實用技巧 >連結串列題python本地除錯

連結串列題python本地除錯

LeetCode某題:用兩個連結串列分別表示兩個正整數,低位在前,高位在後,231表示1->3->2,99表示9->9,會保證末尾不為0,連結串列長度不固定,然後求和,和也是用相同形式的連結串列表示。

該題為例,

class ListNode():
    def __init__(self,x):
        self.val=x
        self.next=None
class SingleLinkList:
    def __init__(self, node=None):
        self.__head = node

    def is_Empty(self):
        
return self.__head is None def append(self, item): # 尾插法 node = ListNode(item) if self.is_Empty(): self.__head = node else: cur = self.__head while cur.next is not None: cur = cur.next cur.next = node
def find_head(self): return self.__head class Solution(): def listsum(self,p,q): flag=0 temp=ListNode(-1) res=temp while p or q or flag: p_val=p.val if p else 0 q_val=q.val if q else 0 temp.next=ListNode((p_val+q_val+flag)%10) flag
=(p_val+q_val+flag)//10 if p:p=p.next if q:q=q.next temp=temp.next return res.next mm = Solution() head = ListNode(None) cur = head for i in [1,2]: cur.next = ListNode(i) cur = cur.next head = head.next head2 = ListNode(None) cur2 = head2 for i in [9,9]: cur2.next = ListNode(i) cur2 = cur2.next head2 = head2.next res = mm.listsum(head,head2) while res: print(res.val, end=' ') res = res.next