Python程序:查找两个给定链表的第一个公共元素
当需要查找两个链表中第一次出现的公共元素时,本文定义了一种向链表添加元素的方法,以及一种查找这两个链表中第一次出现的公共元素的方法。
以下是演示:
示例
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 first_common_val(list_1, list_2):
curr_1 = list_1.head
while curr_1:
data = curr_1.data
curr_2 = list_2.head
while curr_2:
if data == curr_2.data:
return data
curr_2 = curr_2.next
curr_1 = curr_1.next
return None
my_list_1 = LinkedList_structure()
my_list_2 = LinkedList_structure()
my_list = input('Enter the elements of the first linked list : ').split()
for elem in my_list:
my_list_1.add_vals(int(elem))
my_list = input('Enter the elements of the second linked list : ').split()
for elem in my_list:
my_list_2.add_vals(int(elem))
common_vals = first_common_val(my_list_1, my_list_2)
if common_vals:
print('The element that is present first in the first linked list and is common to both is {}.'.format(common))
else:
print('The two lists have no common elements')输出
Enter the elements of the first linked list : 45 67 89 123 45 Enter the elements of the second linked list : 34 56 78 99 0 11 The two lists have no common elements
解释
创建了“Node”类。
创建了另一个具有所需属性的“LinkedList_structure”类。
它有一个“init”函数,用于将第一个元素(即“head”)初始化为“None”。
定义了一个名为“add_vals”的方法,用于向栈添加值。
定义了另一个名为“first_common_val”的方法,用于查找在两个链表中找到的第一个公共值。
创建了两个“LinkedList_structure”实例。
将元素添加到两个链表中。
在这些链表上调用“first_common_value”方法。
结果显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP