📜  链 (1)

📅  最后修改于: 2023-12-03 15:42:07.546000             🧑  作者: Mango

链(Chain)

链是一种常见的数据结构,它由节点(node)和指向下一个节点的指针(pointer)组成。常见的链有单向链、双向链以及循环链。链在程序开发中有着广泛的应用,比如实现链表、队列、栈等数据结构。

单向链表(Singly Linked List)

单向链表是一种最基本的链表,每个节点拥有一个指向下一个节点的指针。它的特点是插入和删除节点非常方便,但是随机访问节点需要遍历整个链表,时间复杂度为$O(n)$。

示例单向链表:

| 1 | -> | 2 | -> | 3 | -> NULL
双向链表(Doubly Linked List)

双向链表比单向链表多了一个指向前一个节点的指针,因此可以双向遍历链表。它的插入和删除操作比单向链表还要方便,但是需要消耗更多的内存空间。

示例双向链表:

NULL <- | 1 | <-> | 2 | <-> | 3 | -> NULL
循环链表(Circular Linked List)

循环链表是指链表的尾节点指向链表的头节点,从而形成一个环。循环链表常用于构建有序列表,或者作为聚集实体(如双向循环链表)。

示例双向循环链表:

NULL <- | 1 | <-> | 2 | <-> | 3 | <-> | 1 | -> NULL
应用案例

链表在程序开发中有着广泛的应用,比如实现队列、栈、哈希表、LRU缓存等数据结构。以LRU缓存为例,它是一种常用的页面置换算法,用于缓存管理机制。基于链表实现的LRU缓存可以用双向链表来实现,它把最近使用的节点移到头部,如果缓存满了,则把最少使用的节点移除。

实现LRU缓存的双向链表伪代码:

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

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = {}
        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self.move_to_head(node)
        return node.val

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.val = value
            self.move_to_head(node)
        else:
            if len(self.cache) == self.capacity:
                tail = self.pop_tail()
                self.cache.pop(tail.key)
            node = Node(key, value)
            self.cache[key] = node
            self.add_to_head(node)

    def add_to_head(self, node: Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def remove_node(self, node: Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def move_to_head(self, node: Node) -> None:
        self.remove_node(node)
        self.add_to_head(node)

    def pop_tail(self) -> Node:
        node = self.tail.prev
        self.remove_node(node)
        return node
总结

链作为一种常见的数据结构,有着广泛的应用。在程序开发中,我们经常需要用到链表、队列、栈等数据结构,而这些数据结构又是基于链表来实现的。使用链表可以提高代码的效率和可读性,对于算法和数据结构的学习也是至关重要的。