Update stack and queue.
This commit is contained in:
@@ -12,64 +12,64 @@ from include import *
|
||||
class MyList:
|
||||
""" 构造函数 """
|
||||
def __init__(self):
|
||||
self._capacity = 10 # 列表容量
|
||||
self._nums = [0] * self._capacity # 数组(存储列表元素)
|
||||
self._size = 0 # 列表长度(即当前元素数量)
|
||||
self._extend_ratio = 2 # 每次列表扩容的倍数
|
||||
self.__capacity = 10 # 列表容量
|
||||
self.__nums = [0] * self.__capacity # 数组(存储列表元素)
|
||||
self.__size = 0 # 列表长度(即当前元素数量)
|
||||
self.__extend_ratio = 2 # 每次列表扩容的倍数
|
||||
|
||||
""" 获取列表长度(即当前元素数量) """
|
||||
def size(self):
|
||||
return self._size
|
||||
return self.__size
|
||||
|
||||
""" 获取列表容量 """
|
||||
def capacity(self):
|
||||
return self._capacity
|
||||
return self.__capacity
|
||||
|
||||
""" 访问元素 """
|
||||
def get(self, index):
|
||||
# 索引如果越界则抛出异常,下同
|
||||
assert index < self._size, "索引越界"
|
||||
return self._nums[index]
|
||||
assert index < self.__size, "索引越界"
|
||||
return self.__nums[index]
|
||||
|
||||
""" 更新元素 """
|
||||
def set(self, num, index):
|
||||
assert index < self._size, "索引越界"
|
||||
self._nums[index] = num
|
||||
assert index < self.__size, "索引越界"
|
||||
self.__nums[index] = num
|
||||
|
||||
""" 中间插入元素 """
|
||||
def add(self, num, index=-1):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
if index == -1:
|
||||
index = self._size
|
||||
index = self.__size
|
||||
# 元素数量超出容量时,触发扩容机制
|
||||
if self._size == self.capacity():
|
||||
if self.__size == self.capacity():
|
||||
self.extend_capacity()
|
||||
# 索引 i 以及之后的元素都向后移动一位
|
||||
for j in range(self._size - 1, index - 1, -1):
|
||||
self._nums[j + 1] = self._nums[j]
|
||||
self._nums[index] = num
|
||||
for j in range(self.__size - 1, index - 1, -1):
|
||||
self.__nums[j + 1] = self.__nums[j]
|
||||
self.__nums[index] = num
|
||||
# 更新元素数量
|
||||
self._size += 1
|
||||
self.__size += 1
|
||||
|
||||
""" 删除元素 """
|
||||
def remove(self, index):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
# 索引 i 之后的元素都向前移动一位
|
||||
for j in range(index, self._size - 1):
|
||||
self._nums[j] = self._nums[j + 1]
|
||||
for j in range(index, self.__size - 1):
|
||||
self.__nums[j] = self.__nums[j + 1]
|
||||
# 更新元素数量
|
||||
self._size -= 1
|
||||
self.__size -= 1
|
||||
|
||||
""" 列表扩容 """
|
||||
def extend_capacity(self):
|
||||
# 新建一个长度为 self._size 的数组,并将原数组拷贝到新数组
|
||||
self._nums = self._nums + [0] * self.capacity() * (self._extend_ratio - 1)
|
||||
# 新建一个长度为 self.__size 的数组,并将原数组拷贝到新数组
|
||||
self.__nums = self.__nums + [0] * self.capacity() * (self.__extend_ratio - 1)
|
||||
# 更新列表容量
|
||||
self._capacity = len(self._nums)
|
||||
self.__capacity = len(self.__nums)
|
||||
|
||||
""" 返回有效长度的列表 """
|
||||
def to_array(self):
|
||||
return self._nums[:self._size]
|
||||
return self.__nums[:self.__size]
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
|
Reference in New Issue
Block a user