📌  相关文章
📜  用于通过更改链接对 0、1 和 2 的链表进行排序的Python程序(1)

📅  最后修改于: 2023-12-03 15:11:18.267000             🧑  作者: Mango

Python程序:用于通过更改链接对0、1和2的链表进行排序

本Python程序旨在通过更改链接来对由0、1和2构成的链表进行排序。链表可以是任何长度。

算法说明

该算法基于Dutch National Flag问题,该问题可以由荷兰国旗中的三个颜色(红色、白色和蓝色)的排序问题进行说明。该算法使用三个指针:头指针,当前指针和尾指针。头指针和当前指针指向链表的头部,尾指针指向链表的尾部。当当前指针遇到0时,与头指针交换节点,并将头指针和当前指针向前移动。当当前指针遇到1时,当前指针向前移动。当当前指针遇到2时,与尾指针交换节点,并将尾指针向后移动。重复此过程,每次移动当前指针直到它到达尾指针为止。

代码实现
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None


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

    def print_list(self):
        current_node = self.head
        while current_node:
            print(current_node.data)
            current_node = current_node.next

    def sort_list(self):
        head_node = self.head
        current_node = self.head
        tail_node = self.head

        while current_node:
            if current_node.data == 0:
                current_node.data, head_node.data = head_node.data, current_node.data
                current_node = current_node.next
                head_node = head_node.next
            elif current_node.data == 2:
                current_node.data, tail_node.data = tail_node.data, current_node.data
                tail_node = tail_node.next
            else:
                current_node = current_node.next

    def add_node(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        last_node = self.head
        while last_node.next:
            last_node = last_node.next

        last_node.next = new_node


linked_list = LinkedList()
linked_list.add_node(2)
linked_list.add_node(0)
linked_list.add_node(1)

linked_list.sort_list()
linked_list.print_list()
用法示例

将该程序保存至.py文件,然后在终端或命令行中运行该程序即可。程序默认对链表进行排序并打印结果。可以根据自己的需要更改添加到链表中的节点数据。

总之,该Python程序提供了一种简单而优雅的方法来对由0、1和2构成的链表进行排序。