https://leetcode-cn.com/problems/implement-queue-using-stacks/

    1. /**
    2. * Your MyQueue object will be instantiated and called as such:
    3. * var obj = new MyQueue()
    4. * obj.push(x)
    5. * var param_2 = obj.pop()
    6. * var param_3 = obj.peek()
    7. * var param_4 = obj.empty()
    8. */
    9. class MyQueue {
    10. private stack1: number[] = []
    11. private stack2: number[] = []
    12. constructor() {
    13. }
    14. push(x: number): void {
    15. this.stack1.push(x)
    16. }
    17. // 从队列的开头移除并返回元素
    18. pop(): number|undefined {
    19. let res;
    20. // 将 stack 移动到 stack2
    21. while (this.stack1.length){
    22. const n = this.stack1.pop()
    23. if (n!== undefined)this.stack2.push(n)
    24. }
    25. res = this.stack2.pop()
    26. while (this.stack2.length){
    27. const n = this.stack2.pop()
    28. if (n!== undefined)this.stack1.push(n)
    29. }
    30. return res || undefined
    31. }
    32. peek(): number | undefined {
    33. if (this.stack1.length > 0) {
    34. return this.stack1[0]
    35. }
    36. }
    37. empty(): boolean {
    38. return this.stack1.length === 0
    39. }
    40. }