链表题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