【发布时间】:2014-08-25 21:51:46
【问题描述】:
我在使用链表上的合并排序时遇到了问题。我发现的问题是我的分区方法 中的问题。
每当我分区并请求前半部分时,另一半结果与前半部分完全相同。但如果我不请求前半部分,后半部分会正确返回。下面是我的代码;
class ListNode:
def __init__(self, x, next = None):
self.val = x
self.next = next
def print_list(root):
while root:
print root.val,
root = root.next
print ''
def partition(root, is_first_half):
print_list(root)
if not root.next:
return root
slow_pointer, fast_pointer = root, root.next
while fast_pointer and fast_pointer.next != None:
fast_pointer = fast_pointer.next.next
slow_pointer = slow_pointer.next
if not is_first_half:
return slow_pointer
first_half, first_half_head, first_half_pointer = None, None, root
while first_half_pointer and first_half_pointer != slow_pointer:
if not first_half_head:
first_half = first_half_pointer
first_half_head = first_half
else:
first_half.next = first_half_pointer
first_half = first_half_pointer
first_half.next = None
first_half_pointer = first_half_pointer.next
return first_half_head
def merge(list1, list2):
new_list_head, new_list = None, None
if not list1:
return list2
if not list2:
return list1
while list1 and list2:
if list1.val < list2.val:
if not new_list_head:
new_list = list1
new_list_head = new_list
else:
new_list.next = list1
new_list = list1
new_list.next = None
list1 = list1.next
else:
if not new_list_head:
new_list = list2
new_list_head = new_list
else:
new_list.next = list2
new_list = list2
new_list.next = None
list2 = list2.next
if not list1:
while list2:
new_list.next = list2
new_list = list2
new_list.next = None
list2 = list2.next
return new_list_head
while list1:
new_list.next = list1
new_list = list1
new_list.next = None
list1 = list1.next
return new_list_head
def mergesort(root):
if not root.next:
return root
list1 = mergesort(partition(root, True))
list2 = mergesort(partition(root, False))
return merge(list1, list2)
if __name__ == '__main__':
a = ListNode(2, ListNode(4, ListNode(3, ListNode(1, ListNode(7)))))
print_list(a)
a = mergesort(a)
print_list(a)
【问题讨论】:
-
你正在丢弃它看起来的列表。在list1 = ...之后放一个'print_list(root)',你会发现整个列表都不存在了。
标签: python algorithm data-structures linked-list partitioning