m0_73756300 2022-12-19 10:11 采纳率: 100%
浏览 26
已结题

用单链表执行快速搜索,但执行快速搜索的函数必须在单链表的class外

用单链表执行快速搜索,输入为搜索前单链表第一个节点(即head)的值,输出为完成搜索后的第一个节点的值,搜索排序为从小到大。注意:搜索函数(quick sort)不能写在class Linked_list内部,只能写在外面,而class Linked_list中也只能有一个init函数和add_first 函数(建立起链表)

  • 写回答

4条回答 默认 最新

  • ShowMeAI 2022-12-19 10:35
    关注

    下面是详细的代码实现,望采纳。
    代码中定义了Node类和LinkedList类,其中Node类表示单链表中的每个节点,LinkedList类表示单链表本身。quick_sort函数用于排序。

    class Node:
        def __init__(self, value=None, next_node=None):
            self.value = value
            self.next_node = next_node
    
    class LinkedList:
        def __init__(self):
            self.head = None
    
        def add_first(self, value):
            self.head = Node(value, self.head)
    
    def quick_sort(head):
        if head is None or head.next_node is None:
            return head
    
        pivot = head.value
        left_list = LinkedList()
        right_list = LinkedList()
    
        current = head.next_node
        while current is not None:
            if current.value < pivot:
                left_list.add_first(current.value)
            else:
                right_list.add_first(current.value)
            current = current.next_node
    
        left_list.head = quick_sort(left_list.head)
        right_list.head = quick_sort(right_list.head)
    
        left_tail = left_list.head
        if left_tail is not None:
            while left_tail.next_node is not None:
                left_tail = left_tail.next_node
            left_tail.next_node = Node(pivot)
            left_tail.next_node.next_node = right_list.head
            return left_list.head
        else:
            head.next_node = right_list.head
            return head
    
    # 示例:使用快速排序对单链表进行排序
    linked_list = LinkedList()
    linked_list.add_first(5)
    linked_list.add_first(4)
    linked_list.add_first(3)
    linked_list.add_first(2)
    linked_list.add_first(1)
    
    sorted_list = quick_sort(linked_list.head)
    
    # 输出排序后的单链表
    current = sorted_list
    while current is not None:
        print(current.value)
        current = current.next_node
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 12月27日
  • 已采纳回答 12月19日
  • 创建了问题 12月19日

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab