Data Structures
in swift programming language…
Part -2:
Queues in swift :
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
These come in handy when we need to handle the objects related to processing, etc.
For Queue type, we need the following methods and variables.
- func enqueue(_ element: Type)
- func dequeue → Type?
- isEmpty: Bool {get}
- peek: Type? {get}
- clearAll()
→ Queue with an Array :
Complexities :
Time complexity:
- For enqueuing an element it is a constant time operation(O(1)), as we are just appending a new element at the end of the storage array.
- For dequeuing an element, we remove the element from storage at the starting, so all the remaining elements have to shift one position left every time we perform the dequeuing operation. So it is linear time operation, and its time complexity is (O(n)).
Space complexity:
- its space complexity is (O(n))
→ Queue with a pair of Stacks :
Complexities :
Time complexity:
- For enqueuing an element it is a constant time operation(O(1)), as we are just appending a new element at the end of the enqueueStack array.
- For dequeuing an element, we remove the element from dequeueStack array from the last, so there will be no performance cost. So it is also constant time operation, and its time complexity is (O(1)).
Space complexity:
- its space complexity is (O(n))