使用 Python 编写静态成员方法实现两个链式存储结构的差运算

本文介绍使用 Python 编写静态成员方法来实现两个链式存储结构的差运算,并返回所求得的差集。

代码示例

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    @staticmethod
    def difference(list1, list2):
        result = LinkedList()
        current1 = list1.head
        while current1:
            if list2.search(current1.data) is None:
                result.insert(current1.data)
            current1 = current1.next
        return result

    def search(self, data):
        current = self.head
        while current:
            if current.data == data:
                return current
            current = current.next
        return None

    def insert(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def display(self):
        current = self.head
        while current:
            print(current.data, end=' ')
            current = current.next
        print()

# 创建链表1
list1 = LinkedList()
list1.insert(1)
list1.insert(2)
list1.insert(3)

# 创建链表2
list2 = LinkedList()
list2.insert(2)
list2.insert(3)
list2.insert(4)

# 计算差集
result = LinkedList.difference(list1, list2)

# 显示结果
result.display()

代码说明

  1. Node 类:表示链表中的节点,包含数据 data 和指向下一个节点的指针 next
  2. LinkedList 类:表示链表,包含头节点 head,以及用于搜索、插入、显示和计算差集的方法。
  3. difference 静态方法:接受两个链表 list1list2 作为参数,返回 list1list2 的差集。
  4. search 方法:在链表中查找指定数据 data,如果找到则返回该节点,否则返回 None
  5. insert 方法:将数据 data 插入链表的尾部。
  6. display 方法:显示链表中的所有数据。

运行结果

运行上述代码,输出结果为:1,即链表1与链表2的差集为1

总结

本文介绍了使用 Python 编写静态成员方法实现两个链式存储结构的差运算,并返回所求得的差集。该方法利用 search 方法判断元素是否在第二个链表中存在,并将不存在的元素插入到结果链表中。代码简洁易懂,可作为学习 Python 数据结构和算法的参考。

Python 静态方法实现链表差集运算

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

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