合并排序中的无限循环错误

时间:2014-02-10 14:36:35

标签: python linked-list

我尝试编写一个函数,用于从两个单链表生成合并排序列表:

def merge_lists(head1, head2):
    if not head1 or not head2:
       return head1 or head2 or []
       head = None
    while head1 is not None and head2 is not None:
          if head is not None and head1 is not None:
             head.next = head1
          else:
              if head is not None and head2 is not None:
                 head.next = head2
          else:
              if head1.value <= head2.value:
                 if not head:
                     head = head1.value
                     head1 = head1.next
                 else:
                    head.next = head1.value
                    head1 = head1.next
              else:
                 if head1.value > head2.value:
                    if not head:
                       head = head2.value
                       head2 = head2.next
                    else:
                       head.next = head2.value
                       head2 = head2.next
    return head

head1和head2是由函数生成的两个链表:

def to_linked_list(plist):
    head = None
    prev = None
for element in plist:
    node = Node(element)
    if not head:
        head = node
    else:
        prev.next = node
    prev = node
return head

从函数merge_lists()返回合并列表的头可以使用例程转换为列表:

def to_linked_list(plist):
head = None
prev = None
for element in plist:
    node = Node(element)
    if not head:
        head = node
    else:
        prev.next = node
    prev = node
return head

当我给两个列表输入为plist1 = [1,2,3]和plist2 = [1,2,3]并将它们转换为链接列表head1和head2并调用merge_lists(0函数,它导致了无限循环。任何人都可以帮助我。

0 个答案:

没有答案