class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Sqlist:
    def __init__(self):
        self.head = None

    def insert_sorted(self, value):
        '''将数据元素按升序插入到链表中。'''
        new_node = Node(value)

        if self.head is None or value <= self.head.data:
            new_node.next = self.head
            self.head = new_node
            return

        current = self.head
        while current.next is not None and value > current.next.data:
            current = current.next

        new_node.next = current.next
        current.next = new_node

    def CreateList(self, a):
        '''创建线性表并使用插入排序对数据进行排序。'''
        for value in a:
            self.insert_sorted(value)

    def printList(self):
        '''遍历并输出链表中的元素。'''
        current = self.head
        while current is not None:
            print(current.data, end='->')
            current = current.next

sql = Sqlist()
x = [15, 20, 1, 9, 2, 6, 7, 3, 22, 32, 8, 11, 14, 100, 87]
sql.CreateList(x)
sql.printList()  # 输出:1->2->3->6->7->8->9->11->14->15->20->22->32->87->100->

这段代码定义了两个类:

  1. Node 类:表示链表中的节点,每个节点存储一个数据元素和指向下一个节点的指针。
  2. Sqlist 类:表示线性表,使用链表进行存储。

Sqlist 类中包含以下方法:

  1. __init__:初始化线性表,初始时链表为空。
  2. insert_sorted:将数据元素按升序插入到链表中,保持链表的有序性。
  3. CreateList:创建线性表,并使用插入排序对数据进行排序。
  4. printList:遍历并输出链表中的元素。

通过调用 CreateList 方法创建线性表并传入待排序的数组,然后调用 printList 方法即可输出排序后的结果。

Python实现线性表链式存储及插入排序

原文地址: https://www.cveoy.top/t/topic/XR3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录