Python 程序检查两个链表是否相同

pythonserver side programmingprogramming更新于 2023/12/27 2:02:00

当需要检查两个链表是否相同时,定义了一种将元素添加到链表的方法,以及一种检查链表中元素相等的方法。

以下是相同的演示 −

示例

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

解释

  • 创建了 ‘Node’ 类。

  • 创建了另一个具有必需属性的 ‘LinkedList_structure’ 类。

  • 它有一个 ‘init’ 函数,用于初始化第一个元素,即将 ‘head’ 初始化为 ‘None’,将 ‘last_node’ 初始化为 ‘None’。

  • 定义了一个名为 ‘add_vals’ 的方法,用于将值添加到堆栈中。

  • 另一个名为 ‘check_equality’ 的方法已定义,它有助于检查两个链接列表中的元素是否相同。

  • 它根据相等性返回 True 或 False。

  • 创建了 ‘LinkedList_structure’ 的两个实例。

  • 将元素添加到两个链接列表中。

  • 在这两个链接列表上调用 ‘check_equality’ 方法。

  • 输出显示在控制台上。


相关文章