เมื่อจำเป็นต้องพิมพ์โหนดสำรองในรายการที่เชื่อมโยงโดยไม่ต้องใช้การเรียกซ้ำ วิธีการเพิ่มองค์ประกอบในรายการที่เชื่อมโยง วิธีการแสดงองค์ประกอบของรายการที่เชื่อมโยง และวิธีการรับค่าอื่นของรายการที่เชื่อมโยง ถูกกำหนดไว้แล้ว
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next
def print_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def alternate_nodes(self):
curr = self.head
while curr:
print(curr.data)
if curr.next is not None:
curr = curr.next.next
else:
break
my_instance = my_linked_list()
my_list = input("Enter the elements of the linked list :").split()
for elem in my_list:
my_instance.add_value(elem)
print("The alternate elements in the linked list are :")
my_instance.alternate_nodes() ผลลัพธ์
Enter the elements of the linked list :56 78 43 51 23 89 0 6 The alternate elements in the linked list are : 56 43 23 0
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
สร้างคลาส "my_linked_list" อีกคลาสที่มีแอตทริบิวต์ที่จำเป็นแล้ว
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และโหนดสุดท้ายเป็น 'None'
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_value' ซึ่งใช้ในการเพิ่มข้อมูลไปยังรายการที่เชื่อมโยง
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งจะวนซ้ำในรายการ และพิมพ์องค์ประกอบ
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'alternate_nodes' ซึ่งกำหนดไว้ซึ่งใช้ในการทำซ้ำผ่านรายการที่เชื่อมโยง
-
วัตถุของคลาส 'my_linked_list' ถูกสร้างขึ้น
-
เรียกเมธอด Alternative_nodes เพื่อค้นหาองค์ประกอบในดัชนีทางเลือก
-
เอาต์พุตนี้จะแสดงบนคอนโซล