用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

python 排序链表

2024-04-24 作者: Python自学举报

[python]代码库

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

def mergeSort(head: ListNode) -> ListNode:
    if head is None or head.next is None:
        return head

    # Find the middle of the linked list
    slow = head
    fast = head.next

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    mid = slow.next
    slow.next = None

    # Recursively split the linked list into two halves
    left = mergeSort(head)
    right = mergeSort(mid)

    # Merge the sorted halves
    dummy = ListNode(0)
    curr = dummy

    while left and right:
        if left.val < right.val:
            curr.next = left
            left = left.next
        else:
            curr.next = right
            right = right.next

        curr = curr.next

    curr.next = left or right

    return dummy.next

# Test the program
head = ListNode(4)
head.next = ListNode(2)
head.next.next = ListNode(1)
head.next.next.next = ListNode(3)

sorted_list = mergeSort(head)

# Print the sorted linked list
curr = sorted_list
while curr:
    print(curr.val)
    curr = curr.next


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...