Stack And Queue In C#




Stack and Queue

Stack 

C# includes a special type of collection which stores elements in LIFO style (Last In First Out). C# includes a generic and non-generic Stack. Here, you are going to learn about the non-generic stack.

Stack myStack = new Stack();
myStack.Push("Hello!!");
myStack.Push(null);
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);

foreach (var itm in myStack)
{
Console.Write(itm);
}

Queue

Queue works on First in first Out (FIFO) basis. And stack works on Last in First Out (LIFO) basis.
Working with Queue. It has two public methods:
Enqueue-Queue Adds an object to the end of the Queue.
Dequeue-Queue Removes and returns the object at the beginning of the


Walkthrough: Keep some integer number to a queue.
Create a new Console application and write the following code.
Class Program
{
Static void Main(string[] args)
{
Queue<int> aQueue = new Queue<int>();
aQueue.Enqueue(100);
aQueue.Enqueue(200);
aQueue.Enqueue(150);
Console.WriteLine(aQueue.Dequeue());
Console.WriteLine(aQueue.Dequeue());

Console.WriteLine(aQueue.Dequeue());
Console.ReadKey();
}
}
You can use foreach to iterate through a Queue. So update your code as follows:
Static void Main(string[] args)
{
Queue<int> aQueue = new Queue<int>;
aQueue.Enqueue(100);
aQueue.Enqueue(200);
aQueue.Enqueue(150);
foreach (int anItem in aQueue)
{
Console.WriteLine(anItem);
}
Console.ReadKey();
}

إرسال تعليق

أحدث أقدم