Python程序将给定的单链表转换为循环链表
当需要将单链表转换为循环链表时,定义了一个名为“convert_to_circular_list”的方法,该方法确保最后一个元素指向第一个元素,从而使其具有循环特性。
以下是相同内容的演示 -
示例
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_struct:
def __init__(self):
self.head = None
self.last_node = None
def add_elements(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def convert_to_circular_list(my_list):
if my_list.last_node:
my_list.last_node.next = my_list.head
def last_node_points(my_list):
last = my_list.last_node
if last is None:
print('The list is empty...')
return
if last.next is None:
print('The last node points to None...')
else:
print('The last node points to element that has {}...'.format(last.next.data))
my_instance = LinkedList_struct()
my_input = input('Enter the elements of the linked list.. ').split()
for data in my_input:
my_instance.add_elements(int(data))
last_node_points(my_instance)
print('The linked list is being converted to a circular linked list...')
convert_to_circular_list(my_instance)
last_node_points(my_instance)输出
Enter the elements of the linked list.. 56 32 11 45 90 87 The last node points to None... The linked list is being converted to a circular linked list... The last node points to element that has 56...
解释
创建“Node”类。
创建另一个具有所需属性的“LinkedList_struct”类。
它有一个“init”函数,用于初始化第一个元素,即“head”为“None”和最后一个节点为“None”。
定义了另一个名为“add_elements”的方法,用于获取链表中的前一个节点。
定义了另一个名为“convert_to_circular_list”的方法,该方法将最后一个节点指向第一个节点,使其具有循环特性。
定义了一个名为“last_node_points”的方法,该方法检查列表是否为空,或者最后一个节点是否指向“None”,或者它是否指向链表的特定节点。
创建“LinkedList_struct”类的对象。
获取用户输入的链表元素。
将元素添加到链表中。
在此链表上调用“last_node_points”方法。
在控制台上显示相关的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP