给定两个链表,任务是创建一个链表来存储链表 1 与链表 2 的差异,即列表 1 中存在但列表 2 中不存在的元素。
例子:
Input:
List1: 10 -> 15 -> 4 ->20,
List2: 8 -> 4 -> 2 -> 10
Output: 15 -> 20
Explanation:
In the given linked list elements 15 and 20 are present in the list 1 but not in list 2.
Input:
List1: 2 -> 4 -> 8 -> 10,
List2: 8 -> 10
Output: 2 -> 4
Explanation:
In the given linked list 1 elements 2 and 4 are present in the list 1 but not in list 2.
方法:
- 使用合并排序对两个链表进行排序。
- 线性扫描两个已排序的链表,得到两个指针 p1 和 p2 的差值,并比较链表中节点的数据,并在以下三种情况下执行以下操作:
- 如果p1.data == p2.data则 p1.data 不能在差异列表中,因此将指针 p1 和 p2 向前移动。
- 如果p1.data > p2.data那么 p1.data 可能会出现在列表 2 的更多节点中,因此将指针 p2 向前移动。
- 如果p1.data > p2.data那么 p1.data 现在不能出现在列表 2 中,因此将 p1 的数据添加到差异列表中并将指针 p1 向前移动。
- 如果到达列表 2 的末尾,则将列表 1 的所有剩余元素插入到差异列表中。
下面是上述方法的实现。
Python
# Python implementation to create
# a difference Linked List of
# two Linked Lists
# Node of the Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Linked List
class linked_list:
def __init__(self):
self.head = None
# Function to insert a node
# at the end of Linked List
def append(self, data):
temp = Node(data)
if self.head == None:
self.head = temp
else:
p = self.head
while p.next != None:
p = p.next
p.next = temp
# Function to find the middle
# node of the Linked List
def get_mid(self, head):
if head == None:
return head
slow = fast = head
while fast.next != None \
and fast.next.next != None:
slow = slow.next
fast = fast.next.next
return slow
# Recursive method to merge the
# two half after sorting
def merge(self, l, r):
if l == None:return r
if r == None:return l
if l.data<= r.data:
result = l
result.next = \
self.merge(l.next, r)
else:
result = r
result.next = \
self.merge(l, r.next)
return result
# Recursive method to divide the
# list into two half until 1 node left
def merge_sort(self, head):
if head == None or head.next == None:
return head
mid = self.get_mid(head)
next_to_mid = mid.next
mid.next = None
left = self.merge_sort(head)
right = self.merge_sort(next_to_mid)
sorted_merge = self.merge(left, right)
return sorted_merge
# Function to print the list elements
def display(self):
p = self.head
while p != None:
print(p.data, end =' ')
p = p.next
print()
# Function to get the difference list
def get_difference(p1, p2):
difference_list = linked_list()
# Scan the lists
while p1 != None and p2 != None:
# Condition to check if the
# Data of the both pointer are
# same then move ahead
if p2.data == p1.data:
p1 = p1.next
p2 = p2.next
# Condition to check if the
# Data of the first pointer is
# greater than second then
# move second pointer ahead
elif p2.data
输出:
2 6 8
时间复杂度: O(M Log M + N Log N)。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live