You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.1 KiB
55 lines
1.1 KiB
/** |
|
* @description 使用两个栈实现一个队列 |
|
* @date 2022-05-11 |
|
*/ |
|
|
|
export class StackQueue { |
|
private stack1: number[] = []; |
|
private stack2: number[] = []; |
|
|
|
add(value: number) { |
|
this.stack1.push(value); |
|
} |
|
|
|
popup() { |
|
if (!this.stack1.length) return; |
|
|
|
while (this.stack1.length) { |
|
const stackValue = this.stack1.pop(); |
|
this.stack2.push(stackValue!); |
|
} |
|
|
|
const popValue = this.stack2.pop(); |
|
|
|
while (this.stack2.length) { |
|
const stackValue = this.stack2.pop(); |
|
this.stack1.push(stackValue!); |
|
} |
|
|
|
return popValue; |
|
} |
|
|
|
get length() { |
|
return this.stack1.length; |
|
} |
|
} |
|
|
|
// console.time("StackQueue"); |
|
// const queue = new StackQueue(); |
|
// for (let index = 0; index < 10000; index++) { |
|
// queue.add(index); |
|
// } |
|
// for (let index = 0; index < 10000; index++) { |
|
// queue.popup(); |
|
// } |
|
// console.timeEnd("StackQueue"); |
|
|
|
// console.time("ArrayQueue"); |
|
// const ArrayQueue = []; |
|
// for (let index = 0; index < 10000; index++) { |
|
// ArrayQueue.push(index); |
|
// } |
|
// for (let index = 0; index < 10000; index++) { |
|
// ArrayQueue.shift(); |
|
// } |
|
// console.timeEnd("ArrayQueue");
|
|
|