python—数据结构—链表合并/逆转

clas

s ListNode(object): def __init__(self,data=0,next=None): self.data=data self.next=next class LinkList(object): def __init__(self): self.head=ListNode(None)#头节点 def Empty(self):#判空 if self.head.next==None: return True else: return False def initwei(self,e):#尾插 p=self.head while p.next: p=p.next q = ListNode(e) p.next=q def ni(self):#逆转 first=self.head.next second=first.next first.next=None self.head.next=None while second: third=second.next second.next=first first=second second=third self.head.next=first def prit(self): p = self.head while p.next != None: print(p.next.data) p=p.next print(' ') def mergeTwoLists(self, l1, l2): if not l1 and not l2: return l1 elif not l1 and l2: return l2 elif l1 and not l2: return l1 tail1 = l1 tail2 = l2 if tail1.data < tail2.data: head = tail1 tail1 = tail1.next head.next = None else: head = tail2 tail2 = tail2.next head.next = None tail = head while (tail1 and tail2): if tail1.data < tail2.data: tail.next = tail1 tail1 = tail1.next tail = tail.next tail.next = None else: tail.next = tail2 tail2 = tail2.next tail = tail.next tail.next = None if tail1: tail.next = tail1 elif tail2: tail.next = tail2 return head if __name__=='__main__': mylist_A=LinkList() for i in range(1, 6): print('input value:') n=int(input()) mylist_A.initwei(n) mylist_A.prit() print ('after reverse:') mylist_A.ni() mylist_A.prit() mylist_B = LinkList() for i in range(1, 6): print('input value:') n = int(input()) mylist_B.initwei(n) mylist_B.prit() print('merge two list') mylist_A.mergeTwoLists(mylist_B.head.next,mylist_A.head.next) mylist_A.prit()