mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
Merge branch 'krahets:master' into typescript
This commit is contained in:
@@ -30,7 +30,7 @@ function extend(nums: number[], enlarge: number): number[] {
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
function insert(nums: number[], num: number, index: number): void {
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (let i = nums.length - 1; i >= index; i--) {
|
||||
for (let i = nums.length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
|
||||
@@ -11,6 +11,7 @@ class ArrayStack {
|
||||
constructor() {
|
||||
this.stack = [];
|
||||
}
|
||||
|
||||
/* 获取栈的长度 */
|
||||
get size(): number {
|
||||
return this.stack.length;
|
||||
@@ -28,16 +29,19 @@ class ArrayStack {
|
||||
|
||||
/* 出栈 */
|
||||
pop(): number | undefined {
|
||||
if (this.empty()) throw new Error('栈为空');
|
||||
return this.stack.pop();
|
||||
}
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
top(): number | undefined {
|
||||
if (this.empty()) throw new Error('栈为空');
|
||||
return this.stack[this.stack.length - 1];
|
||||
}
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
get(index: number): number | undefined {
|
||||
if (index >= this.size) throw new Error('索引越界');
|
||||
return this.stack[index];
|
||||
}
|
||||
|
||||
@@ -83,4 +87,4 @@ console.log("栈的长度 size = " + size);
|
||||
const empty = stack.empty();
|
||||
console.log("栈是否为空 = " + empty);
|
||||
|
||||
export { };
|
||||
export { };
|
||||
|
||||
Reference in New Issue
Block a user