เมื่อจำเป็นต้องแปลงรายการที่เชื่อมโยงเพียงอย่างเดียวเป็นรายการที่เชื่อมโยงแบบวงกลม จะมีการกำหนดวิธีการที่ชื่อ "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...
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
'LinkedList_struct' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และโหนดสุดท้ายเป็น 'None'
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_elements' ซึ่งใช้เพื่อดึงโหนดก่อนหน้าในรายการที่เชื่อมโยง
-
อีกวิธีหนึ่งที่ชื่อว่า 'convert_to_circular_list' ถูกกำหนดให้ชี้โหนดสุดท้ายไปยังโหนดแรก ทำให้มันมีลักษณะเป็นวงกลม
-
มีการกำหนดเมธอดชื่อ 'last_node_points' ซึ่งจะตรวจสอบว่ารายการว่างหรือไม่ หรือโหนดสุดท้ายชี้ไปที่ 'ไม่มี' หรือชี้ไปยังโหนดเฉพาะของรายการที่เชื่อมโยง
-
วัตถุของคลาส 'LinkedList_struct' ถูกสร้างขึ้น
-
ผู้ใช้ป้อนข้อมูลสำหรับองค์ประกอบในรายการที่เชื่อมโยง
-
องค์ประกอบจะถูกเพิ่มลงในรายการที่เชื่อมโยง
-
วิธี 'last_node_points' ถูกเรียกในรายการที่เชื่อมโยงนี้
-
เอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล