python链式全家桶

以下是使用Python实现链式栈操作的代码示例:

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

class Stack:
    def __init__(self):
        self.top = None
    
    def push(self, value):
        new_node = Node(value)
        new_node.next = self.top
        self.top = new_node
    
    def pop(self):
        if self.is_empty():
            return None
        popped_value = self.top.value
        self.top = self.top.next
        return popped_value
    
    def is_empty(self):
        return self.top is None
    
    def peek(self):
        if self.is_empty():
            return None
        return self.top.value

# 创建一个链式栈对象
stack = Stack()

# 将元素压入栈中
stack.push(1)
stack.push(2)
stack.push(3)

# 打印栈顶元素
print(stack.peek())  # 输出: 3

# 弹出栈顶元素
print(stack.pop())  # 输出: 3

# 再次打印栈顶元素
print(stack.peek())  # 输出: 2

# 检查栈是否为空
print(stack.is_empty())  # 输出: False

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个value属性和一个next指针;Stack表示链式栈,包含一个top指针作为栈顶。

通过push方法,可以将新节点插入到栈顶,并调整指针指向。pop方法用于弹出栈顶元素,并返回其值。is_empty方法用于检查栈是否为空。peek方法用于返回栈顶元素的值,而不弹出。

在示例代码中,我们创建了一个链式栈对象stack,并将一些元素压入栈中。通过调用相应的方法,我们可以进行栈操作并输出结果。

以下是使用Python实现链式队列的代码示例:

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

class Queue:
    def __init__(self):
        self.front = None
        self.rear = None
    
    def enqueue(self, value):
        new_node = Node(value)
        if self.is_empty():
            self.front = new_node
            self.rear = new_node
        else:
            self.rear.next = new_node
            self.rear = new_node
    
    def dequeue(self):
        if self.is_empty():
            return None
        dequeued_value = self.front.value
        self.front = self.front.next
        if self.front is None:
            self.rear = None
        return dequeued_value
    
    def is_empty(self):
        return self.front is None
    
    def peek(self):
        if self.is_empty():
            return None
        return self.front.value

# 创建一个链式队列对象
queue = Queue()

# 将元素入队
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)

# 打印队首元素
print(queue.peek())  # 输出: 1

# 出队操作
print(queue.dequeue())  # 输出: 1

# 再次打印队首元素
print(queue.peek())  # 输出: 2

# 检查队列是否为空
print(queue.is_empty())  # 输出: False

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个value属性和一个next指针;Queue表示链式队列,包含一个front指针作为队首,以及一个rear指针作为队尾。

通过enqueue方法,可以将新节点插入到队尾,并调整指针指向。dequeue方法用于从队首弹出元素,并返回其值。is_empty方法用于检查队列是否为空。peek方法用于返回队首元素的值,而不弹出。

在示例代码中,我们创建了一个链式队列对象queue,并将一些元素入队。通过调用相应的方法,我们可以进行队列操作并输出结果。

以下是使用Python实现链式单调队列的代码示例:

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

class MonotonicQueue:
    def __init__(self):
        self.head = None
        self.tail = None
    
    def push(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            while self.tail and self.tail.value < value:
                self.tail = self.tail.next
            if self.tail is None:
                self.head = new_node
                self.tail = new_node
            else:
                new_node.next = self.tail.next
                self.tail.next = new_node
                self.tail = new_node
    
    def pop(self):
        if self.head is None:
            return None
        popped_value = self.head.value
        self.head = self.head.next
        return popped_value
    
    def is_empty(self):
        return self.head is None
    
    def peek(self):
        if self.head is None:
            return None
        return self.head.value

# 创建一个链式单调队列对象
queue = MonotonicQueue()

# 将元素插入队列
queue.push(1)
queue.push(3)
queue.push(2)

# 打印队首元素
print(queue.peek())  # 输出: 1

# 弹出队首元素
print(queue.pop())  # 输出: 1

# 再次打印队首元素
print(queue.peek())  # 输出: 3

# 检查队列是否为空
print(queue.is_empty())  # 输出: False

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个value属性和一个next指针;MonotonicQueue表示链式单调队列,包含一个head指针作为队首,以及一个tail指针作为队尾。

通过push方法,可以将新节点插入到队尾,并保证队列中元素单调递增。具体实现方式是:若队列为空,直接插入节点;否则,从队尾开始向前遍历,移除所有不大于当前值的元素,然后将当前节点插入到队尾。若遍历完成后队列中没有小于当前节点值的元素,则直接插入到队尾。

pop方法用于从队首弹出元素,并返回其值。is_empty方法用于检查队列是否为空。peek方法用于返回队首元素的值,而不弹出。

在示例代码中,我们创建了一个链式单调队列对象queue,并将一些元素插入队列。通过调用相应的方法,我们可以进行单调队列操作并输出结果。

以下是使用Python实现链式优先队列的代码示例:

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

class PriorityQueue:
    def __init__(self):
        self.head = None
    
    def enqueue(self, value, priority):
        new_node = Node(value, priority)
        if self.head is None or priority < self.head.priority:
            new_node.next = self.head
            self.head = new_node
        else:
            current = self.head
            while current.next and priority >= current.next.priority:
                current = current.next
            new_node.next = current.next
            current.next = new_node
    
    def dequeue(self):
        if self.head is None:
            return None
        dequeued_value = self.head.value
        self.head = self.head.next
        return dequeued_value
    
    def is_empty(self):
        return self.head is None
    
    def peek(self):
        if self.head is None:
            return None
        return self.head.value

# 创建一个链式优先队列对象
queue = PriorityQueue()

# 将元素插入队列,同时指定优先级
queue.enqueue("task1", 2)
queue.enqueue("task2", 1)
queue.enqueue("task3", 3)

# 打印队首元素
print(queue.peek())  # 输出: task2

# 弹出队首元素
print(queue.dequeue())  # 输出: task2

# 再次打印队首元素
print(queue.peek())  # 输出: task1

# 检查队列是否为空
print(queue.is_empty())  # 输出: False

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个value属性和一个priority属性,用于存储元素值和优先级;PriorityQueue表示链式优先队列,包含一个head指针作为队首。

通过enqueue方法,可以将新节点插入到合适的位置,以保持队列中的元素按照优先级排序。具体实现方式是:如果队列为空或者新节点的优先级小于队首节点的优先级,直接将新节点作为队首;否则,从队首开始向后遍历,找到合适的位置将新节点插入其中。

dequeue方法用于从队首弹出元素,并返回其值。is_empty方法用于检查队列是否为空。peek方法用于返回队首元素的值,而不弹出。

在示例代码中,我们创建了一个链式优先队列对象queue,并将一些元素插入队列,在插入时指定了优先级。通过调用相应的方法,我们可以进行优先队列操作并输出结果。

链式Set是一种基于链表实现的集合数据结构,其主要特点是插入和删除操作的时间复杂度为O(1),并且不允许包含重复的元素。下面是使用Python实现链式Set的代码示例:

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

class LinkedSet:
    def __init__(self):
        self.head = None
    
    def add(self, value):
        if self.contains(value):
            return False
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
        return True
    
    def remove(self, value):
        if self.head is None:
            return False
        if self.head.value == value:
            self.head = self.head.next
            return True
        current = self.head
        while current.next and current.next.value != value:
            current = current.next
        if current.next:
            current.next = current.next.next
            return True
        return False
    
    def contains(self, value):
        current = self.head
        while current:
            if current.value == value:
                return True
            current = current.next
        return False
    
    def size(self):
        count = 0
        current = self.head
        while current:
            count += 1
            current = current.next
        return count

# 创建一个链式Set对象
set = LinkedSet()

# 添加元素到集合
set.add(1)
set.add(2)
set.add(3)

# 检查集合中是否包含特定元素
print(set.contains(2))  # 输出: True
print(set.contains(4))  # 输出: False

# 从集合中移除元素
set.remove(2)
print(set.contains(2))  # 输出: False

# 获取集合的大小
print(set.size())  # 输出: 2

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个value属性和一个next指针;LinkedSet表示链式Set,包含一个head指针作为链表的头节点。

通过add方法,可以向集合中添加新元素,如果集合已经包含该元素,则不执行任何操作并返回False;否则,创建一个新节点,并将其插入到链表的末尾。

remove方法用于从集合中移除指定元素,如果集合为空,或者集合中不存在该元素,则不执行任何操作并返回False;否则,遍历链表,找到对应节点并删除。

contains方法用于检查集合中是否包含指定元素,通过遍历链表,在找到与该元素相等的节点时返回True,否则返回False。

size方法用于获取集合的大小,通过遍历链表并计数节点的数量来实现。

在示例代码中,我们创建了一个链式Set对象set,并进行了一系列的操作,包括添加元素、检查元素是否存在、移除元素以及获取集合的大小。

链式Map是一种基于链表实现的映射(Map)数据结构,它将键值对存储在节点中,并且可以按照插入顺序进行遍历。下面是使用Python实现链式Map的代码示例:

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

class LinkedMap:
    def __init__(self):
        self.head = None
    
    def put(self, key, value):
        if self.contains(key):
            current = self.head
            while current:
                if current.key == key:
                    current.value = value
                    return
                current = current.next
        new_node = Node(key, value)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
    
    def get(self, key):
        current = self.head
        while current:
            if current.key == key:
                return current.value
            current = current.next
        return None
    
    def remove(self, key):
        if self.head is None:
            return False
        if self.head.key == key:
            self.head = self.head.next
            return True
        current = self.head
        while current.next and current.next.key != key:
            current = current.next
        if current.next:
            current.next = current.next.next
            return True
        return False
    
    def contains(self, key):
        current = self.head
        while current:
            if current.key == key:
                return True
            current = current.next
        return False
    
    def size(self):
        count = 0
        current = self.head
        while current:
            count += 1
            current = current.next
        return count

# 创建一个链式Map对象
map = LinkedMap()

# 添加键值对到映射
map.put("key1", "value1")
map.put("key2", "value2")
map.put("key3", "value3")

# 获取指定键对应的值
print(map.get("key2"))  # 输出: value2
print(map.get("key4"))  # 输出: None

# 更新指定键对应的值
map.put("key2", "new_value")

# 检查映射中是否包含指定键
print(map.contains("key3"))  # 输出: True
print(map.contains("key4"))  # 输出: False

# 移除指定键及其对应的值
map.remove("key1")
print(map.size())  # 输出: 2

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个key属性和一个value属性,用于存储键值对;LinkedMap表示链式Map,包含一个head指针作为链表的头节点。

通过put方法,可以向映射中插入或更新键值对。如果映射中已经包含了给定的键,则更新相应的值;否则,创建一个新节点,并将其插入到链表的末尾。

get方法用于获取指定键对应的值。通过遍历链表,在找到与该键相等的节点时返回对应的值,否则返回None。

remove方法用于从映射中移除指定键及其对应的值。如果映射为空,或者映射中不存在该键,则不执行任何操作并返回False;否则,遍历链表,找到对应节点并删除。

contains方法用于检查映射中是否包含指定键。通过遍历链表,在找到与该键相等的节点时返回True,否则返回False。

size方法用于获取映射中键值对的数量,通过遍历链表并计数节点的数量来实现。

在示例代码中,我们创建了一个链式Map对象map,并进行了一系列的操作,包括添加键值对、获取值、更新值、检查键的存在性、移除键及其对应的值以及获取映射的大小。

链式向量(Linked Vector)是一种基于链表实现的动态数组数据结构。与普通的数组不同,链式向量可以动态地增长和缩小,而不需要提前指定容量。下面是使用Python实现链式向量的代码示例:

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

class LinkedVector:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0
    
    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        self.size += 1
    
    def get(self, index):
        if index < 0 or index >= self.size:
            return None
        current = self.head
        for _ in range(index):
            current = current.next
        return current.data
    
    def set(self, index, data):
        if index < 0 or index >= self.size:
            return False
        current = self.head
        for _ in range(index):
            current = current.next
        current.data = data
        return True
    
    def insert(self, index, data):
        if index < 0 or index > self.size:
            return False
        new_node = Node(data)
        if index == 0:
            new_node.next = self.head
            self.head = new_node
            if self.size == 0:
                self.tail = new_node
        elif index == self.size:
            self.tail.next = new_node
            self.tail = new_node
        else:
            current = self.head
            for _ in range(index - 1):
                current = current.next
            new_node.next = current.next
            current.next = new_node
        self.size += 1
        return True
    
    def remove(self, index):
        if index < 0 or index >= self.size:
            return False
        if index == 0:
            if self.size == 1:
                self.tail = None
            self.head = self.head.next
        else:
            current = self.head
            for _ in range(index - 1):
                current = current.next
            if index == self.size - 1:
                self.tail = current
                current.next = None
            else:
                current.next = current.next.next
        self.size -= 1
        return True
    
    def clear(self):
        self.head = None
        self.tail = None
        self.size = 0

# 创建一个链式向量对象
vector = LinkedVector()

# 在向量末尾追加元素
vector.append("element1")
vector.append("element2")
vector.append("element3")

# 获取指定索引处的元素
print(vector.get(1))  # 输出: element2

# 更新指定索引处的元素
vector.set(1, "new_element")

# 在指定索引处插入元素
vector.insert(0, "new_element_at_start")
vector.insert(3, "new_element_at_end")

# 移除指定索引处的元素
vector.remove(2)

# 清空向量
vector.clear()

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个data属性用于存储数据,以及一个next指针用于指向下一个节点;LinkedVector表示链式向量,包含一个head指针表示链表的头节点,一个tail指针表示链表的尾节点,以及一个size变量表示向量中元素的数量。

通过append方法,可以在向量的末尾追加元素。根据当前链表是否为空,将新节点分别设置为头节点和尾节点,并更新相应的指针和大小。

get方法用于获取指定索引处的元素。通过遍历链表,在找到对应索引处的节点时返回节点的数据,否则返回None。

set方法用于更新指定索引处的元素。通过遍历链表,在找到对应索引处的节点时更新节点的数据。

insert方法用于在指定索引处插入元素。当索引为0时,将新节点设置为头节点,并更新相应的指针和大小。当索引为向量的大小时,将新节点设置为尾节点,并更新相应的指针和大小。其他情况下,先找到索引之前的节点,然后创建新节点并将其插入到链表中。

remove方法用于移除指定索引处的元素。当索引为0时,将头节点指向下一个节点,并更新相应的指针和大小。其他情况下,先找到索引之前的节点,然后将其next指针指向下一个节点的next指针,从而删除当前索引处的节点,并更新相应的指针和大小。

clear方法用于清空链式向量。将头节点、尾节点和大小都重置为初始状态。

在示例代码中,我们创建了一个链式向量对象vector,并进行了一系列的操作,包括追加元素、获取元素、更新元素、插入元素、移除元素和清空向量。

链式二叉树(Linked Binary Tree)是一种基于链表实现的二叉树数据结构。与数组实现的二叉树相比,链式二叉树具有灵活性和动态性。下面是使用Python实现链式二叉树的代码示例:

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

class LinkedBinaryTree:
    def __init__(self):
        self.root = None

    def insert(self, data):
        new_node = TreeNode(data)
        if self.root is None:
            self.root = new_node
        else:
            queue = [self.root]
            while queue:
                node = queue.pop(0)
                if node.left is None:
                    node.left = new_node
                    break
                elif node.right is None:
                    node.right = new_node
                    break
                else:
                    queue.append(node.left)
                    queue.append(node.right)

    def pre_order_traversal(self, node):
        if node is not None:
            print(node.data, end=" ")
            self.pre_order_traversal(node.left)
            self.pre_order_traversal(node.right)

    def in_order_traversal(self, node):
        if node is not None:
            self.in_order_traversal(node.left)
            print(node.data, end=" ")
            self.in_order_traversal(node.right)

    def post_order_traversal(self, node):
        if node is not None:
            self.post_order_traversal(node.left)
            self.post_order_traversal(node.right)
            print(node.data, end=" ")

# 创建一个链式二叉树对象
tree = LinkedBinaryTree()

# 插入节点
tree.insert(1)
tree.insert(2)
tree.insert(3)
tree.insert(4)
tree.insert(5)

# 先序遍历
print("Pre-order traversal:")
tree.pre_order_traversal(tree.root)
print()

# 中序遍历
print("In-order traversal:")
tree.in_order_traversal(tree.root)
print()

# 后序遍历
print("Post-order traversal:")
tree.post_order_traversal(tree.root)
print()

在这个示例中,我们定义了两个类:TreeNode表示二叉树的节点,包含一个data属性用于存储节点的数据,以及左右子节点的指针;LinkedBinaryTree表示链式二叉树,包含一个root指针表示根节点。

通过insert方法,可以向二叉树中插入节点。如果根节点为空,则将新节点设置为根节点。否则,通过广度优先搜索(BFS)找到第一个可用的位置,并将新节点插入。

通过pre_order_traversalin_order_traversalpost_order_traversal方法,可以分别进行先序遍历、中序遍历和后序遍历。这些遍历方法使用递归调用来遍历二叉树的节点,按照遍历顺序输出节点的数据。

在示例代码中,我们创建了一个链式二叉树对象tree,并通过插入方法向树中插入了一些节点。然后,分别进行了先序遍历、中序遍历和后序遍历,并输出遍历结果。

链式图(Linked Graph)是一种基于链表实现的图数据结构。在链式图中,每个顶点都使用链表存储与其相邻的其他顶点。下面是使用Python实现链式图的代码示例:

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

class LinkedGraph:
    def __init__(self):
        self.vertices = {}

    def add_vertex(self, vertex):
        if vertex not in self.vertices:
            self.vertices[vertex] = None

    def add_edge(self, start, end):
        if start in self.vertices and end in self.vertices:
            new_node = Node(end)
            if self.vertices[start] is None:
                self.vertices[start] = new_node
            else:
                current = self.vertices[start]
                while current.next:
                    current = current.next
                current.next = new_node

    def get_neighbors(self, vertex):
        neighbors = []
        if vertex in self.vertices:
            current = self.vertices[vertex]
            while current:
                neighbors.append(current.data)
                current = current.next
        return neighbors

# 创建一个链式图对象
graph = LinkedGraph()

# 添加顶点
graph.add_vertex("A")
graph.add_vertex("B")
graph.add_vertex("C")
graph.add_vertex("D")

# 添加边
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("B", "D")
graph.add_edge("C", "D")

# 获取邻居顶点
print("Neighbors of A:", graph.get_neighbors("A"))  # 输出: Neighbors of A: ['B', 'C']
print("Neighbors of B:", graph.get_neighbors("B"))  # 输出: Neighbors of B: ['D']
print("Neighbors of C:", graph.get_neighbors("C"))  # 输出: Neighbors of C: ['D']
print("Neighbors of D:", graph.get_neighbors("D"))  # 输出: Neighbors of D: []

在这个示例中,我们定义了两个类:Node表示链表节点,包含一个data属性用于存储顶点的数据,以及一个next指针用于指向下一个节点;LinkedGraph表示链式图,包含一个vertices字典,用于存储顶点和其相邻顶点的链表。

通过add_vertex方法,可以向图中添加顶点。如果顶点不存在于vertices字典中,则将其作为键添加到字典中,对应的值设置为None,表示该顶点暂时没有相邻顶点。

通过add_edge方法,可以向图中添加边。首先检查起始顶点和终止顶点是否存在于vertices字典中。然后,将终止顶点作为新节点插入起始顶点对应的链表中。

通过get_neighbors方法,可以获取指定顶点的相邻顶点列表。从vertices字典中找到对应顶点的链表头节点,然后遍历链表添加相邻顶点的数据到列表中。

在示例代码中,我们创建了一个链式图对象graph,并添加了一些顶点和边。接着,通过get_neighbors方法获取了不同顶点的相邻顶点列表,并进行输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值