เมื่อจำเป็นต้องย้อนกลับชุดขององค์ประกอบเฉพาะในรายการที่เชื่อมโยง จะมีการกำหนดวิธีการที่ชื่อ 'reverse_list' ซึ่งจะวนซ้ำผ่านรายการ และย้อนกลับชุดองค์ประกอบเฉพาะ
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_structure:
def __init__(self):
self.head = None
self.last_node = None
def add_vals(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 print_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def reverse_list(my_list, n):
if n == 0:
return
before_val = None
curr = my_list.head
if curr is None:
return
after_val = curr.next
for i in range(n):
curr.next = before_val
before_val = curr
curr = after_val
if after_val is None:
break
after_val = after_val.next
my_list.head.next = curr
my_list.head = before_val
my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
my_instance.add_vals(int(elem))
n = int(input('Enter the number of elements you wish to reverse in the list... '))
reverse_list(my_instance, n)
print('The new list is : ')
my_instance.print_it() ผลลัพธ์
Enter the elements of the linked list... 45 67 89 12 345 Enter the number of elements you wish to reverse in the list... 3 The new list is : 89 67 45 12 345
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
'LinkedList_structure' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None'
-
มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มมูลค่าให้กับสแต็ก
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งช่วยแสดงค่าของรายการที่เชื่อมโยงบนคอนโซล
-
มีการกำหนดวิธีการอื่นที่เรียกว่า "reverse_list" ซึ่งช่วยย้อนกลับชุดองค์ประกอบเฉพาะของรายการที่เชื่อมโยง
-
อินสแตนซ์ของ 'LinkedList_structure' ถูกสร้างขึ้น
-
เพิ่มองค์ประกอบในรายการที่เชื่อมโยง
-
องค์ประกอบจะแสดงบนคอนโซล
-
จำนวนองค์ประกอบที่ต้องย้อนกลับถูกนำมาจากผู้ใช้
-
วิธีการ 'reverse_list' ถูกเรียกในรายการที่เชื่อมโยงนี้
-
เอาต์พุตจะแสดงบนคอนโซล