From 63ad545c64202b21dfbdb6f6d149799ea0b0c27f Mon Sep 17 00:00:00 2001 From: qiuxuewei Date: Wed, 24 Nov 2021 15:33:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20232.=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 0e4a5d6d..6e247d1d 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -349,6 +349,43 @@ MyQueue.prototype.empty = function() { }; ``` +Swift: +```swift +class MyQueue { + + var stackIn = [Int]() + var stackOut = [Int]() + + init() {} + + /** Push element x to the back of queue. */ + func push(_ x: Int) { + stackIn.append(x) + } + + /** Removes the element from in front of queue and returns that element. */ + func pop() -> Int { + if stackOut.isEmpty { + while !stackIn.isEmpty { + stackOut.append(stackIn.popLast()!) + } + } + return stackOut.popLast() ?? -1 + } + + /** Get the front element. */ + func peek() -> Int { + let res = pop() + stackOut.append(res) + return res + } + + /** Returns whether the queue is empty. */ + func empty() -> Bool { + return stackIn.isEmpty && stackOut.isEmpty + } +} +``` -----------------------