Queues act in
a first in, first out (FIFO) fashion, while stacks have last in, first out (LIFO) semantics.
Both have Peek methods that return the next element that would be removed but
without actually removing it. This behavior is demonstrated in listing 3.14.
Queue
queue = new Queue();
Stack stack = new Stack();
for (int i=0; i < 10; i++)
{
queue.Enqueue(i);
stack.Push(i);
}
for (int i=0; i < 10; i++)
{
Console.WriteLine ("Stack:{0} Queue:{1}",
stack.Pop(), queue.Dequeue());
}
The output of listing 3.14 is as follows:
Stack:9 Queue:0
Stack:8 Queue:1
Stack:7 Queue:2
Stack:6 Queue:3
Stack:5 Queue:4
Stack:4 Queue:5
Stack:3 Queue:6
Stack:2 Queue:7
Stack:1 Queue:8
Stack:0 Queue:9
You can enumerate Stack and Queue in the same way as with a list, but in my
experience this is used relatively rarely. Most of the uses I??™ve seen have involved a
thread-safe wrapper being put around either class, enabling a producer/consumer
Listing 3.14 Demonstration of Queue and Stack
101 Generic collection classes in .NET 2.0
pattern for multithreading. This is not particularly hard to write, and third-party
implementations are available, but having these classes directly available in the framework
would be more welcome.
Next we??™ll look at the generic versions of SortedList, which are similar enough to
be twins.
Pages:
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217