[LeetCode] 225. Implement Stack using Queues, Easy

2025. 4. 3. 13:33·CodingTest/LeetCode
반응형

1. 문제

  • 2개의 큐를 사용해서 stack을 구현하라

2.해결

class MyStack {
    inputQueue: number[];
    outputQueue: number[];

    constructor() {
        this.inputQueue = new Array();
        this.outputQueue = new Array();
    }

    push(x: number): void {
        
        while(this.outputQueue.length > 0) {
            this.inputQueue.push(this.outputQueue.shift())
        }

        this.inputQueue.push(x);

        while(this.inputQueue.length > 0) {
            this.outputQueue.push(this.inputQueue.shift())
        }
        
    }

    pop(): number {
        return this.outputQueue.pop()
    }

    top(): number {
        return this.outputQueue[this.outputQueue.length - 1];
    }

    empty(): boolean {
        return this.outputQueue.length === 0
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */
  • 큐의 방향이 반대로 되게 2개를 위치시켰다는 생각으로 구현해봤다.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 733. Flood Fill, Easy
  • [LeetCode] 394. Decode String, Medium
  • [LeetCode] 232. Implement Queue using Stacks, Easy
  • [LeetCode] 94. Binary Tree Inorder Traversal, Easy
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    BOJ
    meidum
    프로그래머스
    자바
    boj1427
    백준1427
    백준1260
    Java
    백준7576자바
    boj2108
    component-scan
    next 14
    leetcode 2236
    백준2751
    알고리즘
    백준
    백준7576
    Easy
    medium
    TypeScript
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 225. Implement Stack using Queues, Easy
상단으로

티스토리툴바