Python程序:对循环链表元素排序
当需要对循环链表的元素进行排序时,需要创建一个名为“Node”的类。在这个类中,有两个属性:节点中存在的数据,以及对链表中下一个节点的访问。
在循环链表中,表头和表尾彼此相邻。它们连接成一个环,最后一个节点没有“NULL”值。
还需要创建另一个名为“linked_list”的类,它将具有一个初始化函数,并且节点的头将初始化为“None”。
用户定义了多个方法来向链表添加节点,按升序或降序对链表进行排序以及打印节点值。
以下是相同的演示 -
示例
class Node:
def __init__(self,data):
self.data = data
self.next = None
class list_creation:
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.next = self.head
def add_data(self,my_data):
new_node = Node(my_data)
if self.head.data is None:
self.head = new_node
self.tail = new_node
new_node.next = self.head
else:
self.tail.next = new_node
self.tail = new_node
self.tail.next = self.head
def sort_list(self):
curr = self.head
if(self.head == None):
print("The list is empty")
else:
while(True):
index_val = curr.next
while(index_val != self.head):
if(curr.data > index_val.data):
temp = curr.data
curr.data = index_val.data
index_val.data = temp
index_val = index_val.next
curr =curr.next
if(curr.next == self.head):
break;
def print_it(self):
curr = self.head
if self.head is None:
print("The list is empty");
return;
else:
print(curr.data)
while(curr.next != self.head):
curr = curr.next
print(curr.data)
print("\n")
class circular_linked_list:
my_cl = list_creation()
print("Nodes are being added to the list")
my_cl.add_data(21)
my_cl.add_data(54)
my_cl.add_data(78)
my_cl.add_data(99)
my_cl.add_data(27)
print("The list is :")
my_cl.print_it()
print("The list is being sorted")
my_cl.sort_list()
print("The sorted list is : ")
my_cl.print_it()输出
Nodes are being added to the list The list is : 21 54 78 99 27 The list is being sorted The sorted list is : 21 27 54 78 99
解释
- 创建了“Node”类。
- 创建了另一个具有所需属性的类。
- 定义了另一个名为“sort_list”的方法,用于按升序或降序对循环链表中的元素进行排序。
- 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
- 创建了“list_creation”类的对象,并在其上调用方法以添加数据。
- 定义了一个“init”方法,将循环链表的第一个和最后一个节点设置为None。
- 调用了“sort_list”方法。
- 它遍历列表,并根据值将元素放置在其相关位置。
- 使用“print_it”方法在控制台上显示。
广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP