0%
题目如下
思路如下
- 将数据A、B、C入栈到stackA中
- 将stackA中的数据出栈(C-B-A),入栈到stackB中,此时stackB中的栈顶到栈底的数据依次为 A、B、C,此时可以通过stackB做出栈,即输出A,达到队列的效果
- 在stackB出栈后,需要将stackB栈中剩余的数据重新入栈到stackA中,以保持数据原来的顺序不变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| export class TwoStacksToQueue { private stack1: number[] = [] private stack2: number[] = [] add(n:number) { this.stack1.push(n) } delete() :number | null { let res const stack1 = this.stack1 const stack2 = this.stack2 while(stack1.length){ const n = stack1.pop() if(n != null){ stack2.push(n) } } res = stack2.pop() while(stack2.length){ const n = stack2.pop() if(n !=null){ stack1.push(n) } } return res || null } get length():number { return this.stack1.length } }
|
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
import { TwoStacksToQueue } from './two-stacks-one-queue'
describe('两个栈,一个队列', () => { it('add and length', () => { const q = new TwoStacksToQueue() expect(q.length).toBe(0)
q.add(100) q.add(200) q.add(300) expect(q.length).toBe(3) })
it('delete', () => { const q = new TwoStacksToQueue() expect(q.delete()).toBeNull()
q.add(100) q.add(200) q.add(300) expect(q.delete()).toBe(100) expect(q.length).toBe(2) expect(q.delete()).toBe(200) expect(q.length).toBe(1) }) })
|