zoukankan      html  css  js  c++  java
  • python使用数组实现链表的策略分析

    python实现链表数据结构:数组/节点与引用

    使用数组策略

    • 使用数组存储指向其他对象的引用
    • 数组存储空间过度分配
    • 数组填满后,分配一个更大的数组,将旧数组的内容复制到新数组中
    class ArrayList:
        def __init__(self):
            self.size_exponent = 0
            self.max_size = 0  # 记录当前数组大小
            self.last_index = 0  # 记录当前列表的末尾索引
            self.my_array = []   # 模拟数组
         
        # 末尾添加元素   
        def append(self, val):
            if self.last_index > self.max_size - 1:
                self.resize()
            self.my_array[self.last_index] = val
            self.last_index += 1
        
        # 确定位置插入元素
        def insert(self, idx, val):
            if self.last_index > self.max_size - 1:
                self.__resize()
            for i in range(self.last_index, idx - 1, -1):
                self.my_array[i + 1] = self.my_array[i]
            self.last_index += 1
            self.my_array[idx] = val
        
        # 数组扩容
        def __resize(self):
            new_size = 2 ** self.size_exponent
            new_array = [0] * new_size
            for i in range(self.max_size):
                new_array[i] = self.my_array[i]   # 将旧数组复制到新数组中
            
            self.max_size = new_size
            self.my_array = new_array
            self.size_exponent += 1
            
        # 根据索引获取值
        def __get_item__(self, idx):
            if idx < self.last_index:
                return self.my_array[idx]
            else:
                raise LookupError('index out of bounds')
        
        # 修改列表的值
        def __set_item__(self, idx, val):
            if idx < self.last_index:
                self.my_array[idx] = val
            else:
                raise LookupError('index out of bounds')
  • 相关阅读:
    Business Objects 基础
    常用的bw基础知识
    SAP BW传输请求操作步骤
    FI/CO 财务基础知识
    SAP财务常用数据源概览
    HANA 和 SAP NetWeaver BW
    Request.QueryString中文乱码
    完全备份类型
    SQL Server备份属于I/O密集型操作
    SQL Server 通过发布订阅 实现数据库同步
  • 原文地址:https://www.cnblogs.com/donghe123/p/12937163.html
Copyright © 2011-2022 走看看