下面我将手写一个简化的List容器核心函数实现,包含插入、删除和查找功能。使用Python语言实现,基于动态数组原理:

class MyList:
    def __init__(self):
        # 初始容量为2
        self.capacity = 2
        # 存储数据的数组
        self.data = [None] * self.capacity
        # 当前元素数量
        self.size = 0
    
    def _resize(self, new_capacity):
        """内部方法:调整数组大小"""
        new_data = [None] * new_capacity
        # 复制旧数据
        for i in range(self.size):
            new_data[i] = self.data[i]
        self.data = new_data
        self.capacity = new_capacity
    
    def insert(self, index, value):
        """在指定位置插入元素"""
        if index < 0 or index > self.size:
            raise IndexError("索引超出范围")
        
        # 检查是否需要扩容
        if self.size == self.capacity:
            self._resize(self.capacity * 2)
        
        # 移动元素腾出空间
        for i in range(self.size, index, -1):
            self.data[i] = self.data[i-1]
        
        # 插入新元素
        self.data[index] = value
        self.size += 1
    
    def remove(self, index):
        """删除指定位置的元素"""
        if index < 0 or index >= self.size:
            raise IndexError("索引超出范围")
        
        # 保存被删除的值
        removed = self.data[index]
        
        # 移动元素覆盖被删除位置
        for i in range(index, self.size-1):
            self.data[i] = self.data[i+1]
        
        self.size -= 1
        # 检查是否需要缩容
        if self.size <= self.capacity // 4 and self.capacity > 2:
            self._resize(self.capacity // 2)
        
        return removed
    
    def find(self, value):
        """查找元素首次出现的位置"""
        for i in range(self.size):
            if self.data[i] == value:
                return i
        return -1  # 未找到
    
    def __str__(self):
        """字符串表示"""
        return "[" + ", ".join(str(self.data[i]) for i in range(self.size)) + "]"

核心功能说明:

  1. 插入操作

    • 时间复杂度:$O(n)$
    • 实现原理:
      • 检查索引有效性
      • 动态扩容(当空间不足时)
      • 移动后续元素腾出位置
      • 插入新元素
  2. 删除操作

    • 时间复杂度:$O(n)$
    • 实现原理:
      • 检查索引有效性
      • 移动后续元素覆盖删除位置
      • 动态缩容(空间利用率过低时)
  3. 查找操作

    • 时间复杂度:$O(n)$
    • 实现原理:
      • 线性遍历数组
      • 返回第一个匹配元素的索引

使用示例:

lst = MyList()
lst.insert(0, 10)  # [10]
lst.insert(1, 20)  # [10, 20]
lst.insert(1, 15)  # [10, 15, 20]

print(lst.find(15))  # 输出: 1
print(lst.remove(1))  # 输出: 15,列表变为[10, 20]

此实现包含了动态数组的核心特性:

  • 自动扩容/缩容机制
  • 连续内存存储
  • 随机访问能力
  • 高效的尾部操作(未展示但可扩展)

更多推荐