用于链接列表的Mergesort的Python实现不起作用

时间:2016-09-05 20:38:18

标签: python algorithm sorting linked-list mergesort

我无法在Python中为Merge Sort找到Linked Lists的简单实现。这就是我的尝试:

单链表的定义:

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

合并排序实施:

def mergeSortLinkedList(A):
    # Base case length of 0 or 1:
    if A == None or A.next == None:
        return A

    leftHalf, rightHalf = splitTheList(A)

    mergeSortLinkedList(leftHalf)
    mergeSortLinkedList(rightHalf)

    # The above two lines should be modified to the following. Thanks to the answers.

    # leftHalf  = mergeSortLinkedList(leftHalf)
    # rightHalf = mergeSortLinkedList(rightHalf)

    return mergeTheLists(leftHalf, rightHalf)

分割:

def splitTheList(sourceList):
    if sourceList == None or sourceList.next == None:
        leftHalf = sourceList
        rightHalf = None

        return leftHalf, rightHalf

    else:
        midPointer = sourceList
        frontRunner = sourceList.next
        # totalLength += 1        - This is unnecessary

        while frontRunner != None:
            frontRunner = frontRunner.next

            if frontRunner != None:
                frontRunner = frontRunner.next
                midPointer = midPointer.next

    leftHalf = sourceList
    rightHalf = midPointer.next
    midPointer.next = None

    return leftHalf, rightHalf

合并:

def mergeTheLists(leftHalf, rightHalf):
    fake_head = ListNode(None)
    curr = fake_head

    while leftHalf and rightHalf:
        if leftHalf.val < rightHalf.val:
            curr.next = leftHalf
            leftHalf = leftHalf.next

        else:
            curr.next = rightHalf
            rightHalf = rightHalf.next

        curr = curr.next

    if leftHalf == None:
        curr.next = rightHalf

    elif rightHalf == None:
        curr.next = leftHalf

    return fake_head.next

数据:

# Node A:
nodeA1 = ListNode(2)

nodeA2 = ListNode(1)
nodeA1.next = nodeA2

nodeA3 = ListNode(9)
nodeA2.next = nodeA3

nodeA4 = ListNode(3)
nodeA3.next = nodeA4

# Node C:
nodeC1 = ListNode(5)
nodeA4.next = nodeC1

nodeC2 = ListNode(6)
nodeC1.next = nodeC2

nodeC3 = ListNode(4)
nodeC2.next = nodeC3

nodeC4 = ListNode(5)
nodeC3.next = nodeC4

调用mergeSortLinkedList(nodeA1)时的预期输出:

1 2 3 4 5 5 6 9

我得到以下内容:

2 5 6 9

我无法弄清楚错过的位置。请帮忙。

2 个答案:

答案 0 :(得分:3)

您不使用递归调用的返回值。代码应该是:

def mergeSortLinkedList(A):
    if A is None or A.next is None:
        return A

    leftHalf, rightHalf = splitTheList(A)

    left = mergeSortLinkedList(leftHalf)
    right = mergeSortLinkedList(rightHalf)

    return mergeTheLists(left, right)

在调用函数之后,某些情况下的参数不会指向排序列表的头部。

代码中的下一个错误是使用未定义的变量totalLength。

答案 1 :(得分:2)

尝试将mergeSort函数中的行更改为:

func openTableViewCells<T:UIView>(inout theSwitch: Bool, inout array: [T]) {


switch theSwitch {
case false:
    for i in array {
        i.hidden = true
    }
    theSwitch = true
case true:
    for i in array {
        i.hidden = false
    }
    theSwitch = false
}
}