Queue
In this chapter you will learn:
Generic Queue and Non-generic Queue
Queue<T>
and Queue are first-in first-out (FIFO) data structures,
providing methods to Enqueue (add an item to the tail of the queue)
and Dequeue (retrieve and remove the item at the head of the queue).
A Peek method is also provided to return the element at the head of
the queue without removing it, and a Count property.
The following code shows how to do enqueue and dequeue operations.
using System; //from java 2 s .co m
using System.Collections;
class MainClass {
public static void Main() {
Queue q = new Queue();
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
Console.Write("queue: ");
foreach(int i in q)
Console.Write(i + " ");
Console.WriteLine();
Console.Write("Dequeue -> ");
int a = (int) q.Dequeue();
Console.WriteLine(a);
Console.Write("queue: ");
foreach(int i in q)
Console.Write(i + " ");
Console.WriteLine();
}
}
The code above generates the following result.
Clear a Queue
using System;/*from j a va 2 s.c o m*/
using System.Collections;
class MainClass
{
static void Main(string[] args)
{
Queue a = new Queue(10);
int x = 0;
a.Enqueue(x);
x++;
a.Enqueue(x);
foreach (int y in a)
{
Console.WriteLine(y);
}
a.Dequeue();
a.Clear();
}
}
The code above generates the following result.
Peek a queue
using System;/*ja v a2s. c om*/
using System.Collections;
using System.Collections.Specialized;
class MyClass{
public string MyName="A";
}
class MainClass
{
static void Main(string[] args)
{
Queue classQueue = new Queue();
classQueue.Enqueue(new MyClass());
classQueue.Enqueue(new MyClass());
classQueue.Enqueue(new MyClass());
// Peek at first car in Q.
Console.WriteLine("First in Q is {0}",
((MyClass)classQueue.Peek()).MyName);
}
}
Next chapter...
What you will learn in the next chapter:
- How to add element to a generic Queue
- Creating a list from a queue
- How to remove element from a generic Queue
Home » C# Tutorial » Collections