以下是实现单链表的查询、插入、删除的三个函数的示例代码:

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

class LinkedList:
    def __init__(self):
        self.head = 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 delete(self, data):
        if self.head is None:
            return
        if self.head.data == data:
            self.head = self.head.next
        else:
            current = self.head
            while current.next:
                if current.next.data == data:
                    current.next = current.next.next
                    return
                current = current.next

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

使用示例:

linked_list = LinkedList()

linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.insert(4)

print(linked_list.search(3))  # 输出: True

linked_list.delete(3)

print(linked_list.search(3))  # 输出: False

这个示例中,我们首先创建了一个LinkedList对象linked_list,然后调用insert方法插入了4个节点(数据为1、2、3、4)。接着,我们调用search方法查询数据3是否存在于链表中,结果为True。最后,我们调用delete方法删除数据为3的节点,并再次调用search方法查询数据3是否存在于链表中,结果为False。

解释:

  • Node 类: 每个节点包含数据 data 和指向下一个节点的指针 next
  • LinkedList 类: 表示整个链表,包含指向头节点的指针 head
  • insert 方法: 插入新节点,如果链表为空,则将新节点作为头节点;否则遍历链表找到最后一个节点,并将新节点连接到最后一个节点的 next 指针。
  • delete 方法: 删除指定数据节点,如果头节点就是目标节点,则更新头节点指针;否则遍历链表找到目标节点的前一个节点,并将前一个节点的 next 指针指向目标节点的下一个节点。
  • search 方法: 遍历链表,查找指定数据节点,如果找到则返回 True,否则返回 False

通过以上代码示例,我们可以更好地理解单链表的基本操作和实现方法。单链表是一种简单但灵活的数据结构,在实际应用中有着广泛的应用。

Python 单链表实现:查询、插入和删除操作

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

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