เมื่อจำเป็นต้องตรวจสอบว่ารายชื่อที่เชื่อมโยงเพียงอย่างเดียวคือพาลินโดรมหรือไม่ วิธีการเพิ่มองค์ประกอบ รับโหนดก่อนหน้า และตรวจสอบว่ามีการกำหนดพาลินโดรมเกิดขึ้นหรือไม่
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
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 get_previous_node(self, ref_node):
curr = self.head
while (curr and curr.next != ref_node):
curr = curr.next
return curr
def check_palindrome(my_list):
beg = my_list.head
end = my_list.last_node
while (beg != end and end.next != beg):
if beg.data != end.data:
return False
beg = beg.next
end = my_list.get_previous_node(end)
return True
my_instance = LinkedList_struct()
my_input = input('Enter elements to the linked list: ').split()
for data in my_input:
my_instance.add_elements(int(data))
if check_palindrome(my_instance):
print('The linked list is palindromic in nature')
else:
print('The linked list is not palindromic in nature') ผลลัพธ์
Enter elements to the linked list: 89 90 78 90 89 The linked list is palindromic in nature
คำอธิบาย
-
สร้างคลาส "โหนด" แล้ว
-
'LinkedList_struct' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น
-
มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และโหนดสุดท้ายเป็น 'None'
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_elements' ซึ่งใช้เพื่อดึงโหนดก่อนหน้าในรายการที่เชื่อมโยง
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'get_previous_node' ซึ่งใช้ในการแสดงข้อมูลรายการที่เชื่อมโยงบนคอนโซล
-
มีการกำหนดเมธอดที่ชื่อว่า 'check_palindrome' ซึ่งเปรียบเทียบองค์ประกอบแรกและองค์ประกอบสุดท้าย หากไม่เหมือนกัน แสดงว่ารายการไม่ได้มีลักษณะเป็นพาลินโดรม
-
วัตถุของคลาส 'LinkedList_struct' ถูกสร้างขึ้น
-
ผู้ใช้ป้อนข้อมูลสำหรับองค์ประกอบในรายการที่เชื่อมโยง
-
องค์ประกอบจะถูกเพิ่มลงในรายการที่เชื่อมโยง
-
วิธีการ 'check_palindrome' ถูกเรียกในรายการที่เชื่อมโยงนี้
-
เอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล