实现思路:

1.将A、B两个链表中的元素添加到一个新链表C中,同时去重。

2.返回链表C。

时间复杂度:O(n)

空间复杂度:O(n)

Python代码实现如下:

class Node: def init(self, val=None, next=None): self.val = val self.next = next

class Solution: def getUnion(self, head1, head2): if not head1: return head2 if not head2: return head1

    # 将链表1的元素添加到链表C中
    C = head1
    tail = head1
    node = head1.next
    while node:
        if not self.isExist(head1, node.val):
            tail.next = node
            tail = node
        node = node.next
    
    # 将链表2的元素添加到链表C中
    node = head2
    while node:
        if not self.isExist(head1, node.val):
            tail.next = node
            tail = node
        node = node.next
    
    return C

# 判断链表中是否存在某个元素
def isExist(self, head, val):
    node = head
    while node:
        if node.val == val:
            return True
        node = node.next
    return False

测试代码

head1 = Node(1, Node(3, Node(2))) head2 = Node(5, Node(1, Node(4, Node(2)))) s = Solution() C = s.getUnion(head1, head2) node = C while node: print(node.val) node = node.next

输出:1 3 2 5 4

有两个集合采用整数单链表A、B存储设计一个算法求两个集合的并集CC仍然用单链表存储并给出算法的时间和空间复杂度。例如 A=132B=5142并集C=13254。python

原文地址: http://www.cveoy.top/t/topic/bp0d 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录