mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-16 03:59:18 +08:00
Fix the index out of bound check in my_list.
This commit is contained in:
@@ -29,24 +29,23 @@ class MyList {
|
||||
/* 访问元素 */
|
||||
public get(index: number): number {
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index >= this._size) {
|
||||
if (index < 0 || index >= this._size)
|
||||
throw new Error('索引越界');
|
||||
}
|
||||
return this.nums[index];
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
public set(index: number, num: number): void {
|
||||
if (index >= this._size) throw new Error('索引越界');
|
||||
if (index < 0 || index >= this._size)
|
||||
throw new Error('索引越界');
|
||||
this.nums[index] = num;
|
||||
}
|
||||
|
||||
/* 尾部添加元素 */
|
||||
public add(num: number): void {
|
||||
// 如果长度等于容量,则需要扩容
|
||||
if (this._size === this._capacity) {
|
||||
if (this._size === this._capacity)
|
||||
this.extendCapacity();
|
||||
}
|
||||
// 将新元素添加到列表尾部
|
||||
this.nums[this._size] = num;
|
||||
this._size++;
|
||||
@@ -54,9 +53,8 @@ class MyList {
|
||||
|
||||
/* 中间插入元素 */
|
||||
public insert(index: number, num: number): void {
|
||||
if (index >= this._size) {
|
||||
if (index < 0 || index >= this._size)
|
||||
throw new Error('索引越界');
|
||||
}
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (this._size === this._capacity) {
|
||||
this.extendCapacity();
|
||||
@@ -72,7 +70,8 @@ class MyList {
|
||||
|
||||
/* 删除元素 */
|
||||
public remove(index: number): number {
|
||||
if (index >= this._size) throw new Error('索引越界');
|
||||
if (index < 0 || index >= this._size)
|
||||
throw new Error('索引越界');
|
||||
let num = this.nums[index];
|
||||
// 将索引 index 之后的元素都向前移动一位
|
||||
for (let j = index; j < this._size - 1; j++) {
|
||||
|
||||
Reference in New Issue
Block a user