Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python เช็ค 2 Linked Lists เหมือนกัน


เมื่อจำเป็นต้องตรวจสอบว่ารายการที่เชื่อมโยงสองรายการเหมือนกันหรือไม่ วิธีการเพิ่มองค์ประกอบในรายการที่เชื่อมโยง และวิธีการตรวจสอบความเท่าเทียมกันขององค์ประกอบในรายการที่เชื่อมโยงจะถูกกำหนด

ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -

ตัวอย่าง

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 check_equality(list_1, list_2):
   curr_1 = list_1.head
   curr_2 = list_2.head
   while (curr_1 and curr_2):
      if curr_1.data != curr_2.data:
         return False
      curr_1 = curr_1.next
      curr_2 = curr_2.next
   if curr_1 is None and curr_2 is None:
      return True
   else:
      return False

my_linked_list_1 = LinkedList_structure()
my_linked_list_2 = LinkedList_structure()

my_list = input('Enter the elements of the first linked list: ').split()
for elem in my_list:
   my_linked_list_1.add_vals(int(elem))

my_list = input('Enter the elements of the second linked list: ').split()
for elem in my_list:
   my_linked_list_2.add_vals(int(elem))

if check_equality(my_linked_list_1, my_linked_list_2):
   print('The two linked lists are the same')
else:
   print('The two linked list are not same')

ผลลัพธ์

Enter the elements of the first linked list: 34 56 89 12 45
Enter the elements of the second linked list: 57 23 78 0 2
The two linked list are not same

คำอธิบาย

  • สร้างคลาส "โหนด" แล้ว

  • 'LinkedList_structure' คลาสอื่นพร้อมแอตทริบิวต์ที่จำเป็นจะถูกสร้างขึ้น

  • มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และ 'last_node' เป็น 'None'

  • มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มมูลค่าให้กับสแต็ก

  • มีการกำหนดวิธีการอื่นที่เรียกว่า 'check_equality' ซึ่งช่วยตรวจสอบว่าองค์ประกอบในสองรายการที่เชื่อมโยงเหมือนกันหรือไม่

  • คืนค่า True หรือ False ขึ้นอยู่กับความเท่าเทียมกัน

  • 'LinkedList_structure' สองอินสแตนซ์ถูกสร้างขึ้น

  • องค์ประกอบจะถูกเพิ่มลงในสองรายการที่เชื่อมโยง

  • วิธีการ 'check_equality' ถูกเรียกใช้ในรายการที่เชื่อมโยงทั้งสองนี้

  • เอาต์พุตจะแสดงบนคอนโซล