-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
225 Implement Stack using Queues.swift
67 lines (58 loc) · 1.64 KB
/
225 Implement Stack using Queues.swift
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// 225 Implement Stack using Queues.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 28/02/2021.
// Copyright © 2021 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/implement-stack-using-queues/
class MyStack {
private var queue: [Int]
init() {
queue = [Int]()
}
/// Push element x onto stack.
///
/// - Parameter x: New element.
///
/// - Complexity:
/// - time: O(n), where n is the number of elements in the stack.
/// - space: O(1), only constant space is used.
func push(_ x: Int) {
queue.append(x)
for _ in 1..<queue.count {
queue.append(queue.removeFirst())
}
}
/// Removes the element on top of the stack and returns that element.
///
/// - Returns: The element on top of the stack.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func pop() -> Int {
queue.removeFirst()
}
/// Get the top element.
///
/// - Returns: The top element.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func top() -> Int {
queue.first ?? -1
}
/// Returns whether the stack is empty.
///
/// - Returns: True if the stack is empty, otherwise returns false.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func empty() -> Bool {
queue.isEmpty
}
}