You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Most of the new functionality sits in `dequeue()`. When we dequeue an item, we first set `array[head]`to`nil`to remove the object from the array. Then we increment `head`because now the next item has become the front one.
It's like some weird supermarket where the people in the checkout lane don't shuffle forward towards the cash register, but the cash register moves up the queue.
193
+
这就像在某个外星球的奇怪超市,在那里排队结账的人保持不动,而收银员往队尾移动来挨个结账。
194
194
195
-
Of course, if we never remove those empty spots at the front then the array will keep growing as we enqueue and dequeue elements. To periodically trim down the array, we do the following:
@@ -202,12 +202,14 @@ Of course, if we never remove those empty spots at the front then the array will
202
202
}
203
203
```
204
204
205
-
This calculates the percentage of empty spots at the beginning as a ratio of the total array size. If more than 25% of the array is unused, we chop off that wasted space. However, if the array is small we don't want to resize it all the time, so there must be at least 50 elements in the array before we try to trim it.
Now if you dequeue another object, the array will look as follows:
248
+
现在,如果你再次执行出队操作,数组将看起来像下面这样:
247
249
248
250
```swift
249
251
q.dequeue() // "Tim"
250
252
q.array// [{Some "Grace"}]
251
253
q.count// 1
252
254
```
253
255
254
-
The `nil` objects at the front have been removed and the array is no longer wasting space. This new version of `Queue` isn't much more complicated than the first one but dequeuing is now also an **O(1)** operation, just because we were a bit smarter about how we used the array.
There are many other ways to create a queue. Alternative implementations use a [linked list](../Linked List/), a [circular buffer](../Ring Buffer/), or a [heap](../Heap/).
Variations on this theme are [deque](../Deque/), a double-ended queue where you can enqueue and dequeue at both ends, and [priority queue](../Priority Queue/), a sorted queue where the "most important" item is always at the front.
0 commit comments