SIGN UP MEMBER LOGIN:    
ARTICLE

Stack and Queue in C#

Posted by Sivaraman Dhamodaran Articles | C# Language November 05, 2010
In this article you will learn how to implement stacks and queues using C#.
Reader Level:
Download Files:
 

Introduction


Both Stack and Queue are collection classes supported by the .Net framework. Queue operates on First in First Out (FIFO) principle. Stack operates on Last in First out (LIFO) principle. That is; when you remove an item from the Queue, the first item added will be removed first. In the case of Stack it is in the reverse order, I mean, the item added last is removed first.

 

To use Stack and Queue in your application first include the name space System.Collections.
 

//000: Use the Collection namespace to have access to collection classes

using System.Collections;

 

Using Queue Class- Built-in

 

We start using Queue and Stack in our Static Main method. First let us go with Queue.
 

1. A Queue is created and 5 integers are stored in it. The Queue class's Enqueue() function is used to add an element at theback of the Q.


 

//===============> A. Queue  <==================

Console.WriteLine("===============> A. Queue  <==================");

//A_001: Create a Queue and populate it.

Queue Q = new Queue();

 

//A_002: populate 5 Integers to it. Enqueue adds an element to the Queue and the End.

for (int i=0; i<5; i++)

            Q.Enqueue(i+1);

 

2. To display all the elements in the Queue a function was written. The function takes IEnumerable interface as parameter meaning that the function expects an object that implemented the IEnumerable interface. Then, it walks through the collection object (Stack or Queue in this Example. Say thanks to polymorphism) and displays each element in it.


 

//001: Display the passed in collection. Note the collection Stack, Queue, Hash all implements IEnumerable

public static void DisplayContent(string collection_name, IEnumerable collection )

{

            Console.Write("Content of {0}: ", collection_name );

            foreach(int item in collection)

                        Console.Write(item + ", " );

            Console.WriteLine();

}

 


 

3. The Peek() method will return the first item in the Queue. That is; it will get the element first added (One that is there in the Front). However, Peek() method will not remove the item from the Queue. But, the Dequeue() will take the item from the front and removes it. The usage of Peek() and Dequeue() is shown in the following Code:


 

//A_003: Show the Queue Content

DisplayContent("Queue", Q );

 

//A_004: Return the Object at the begining of the Queue

Console.WriteLine("First element: {0}", Q.Peek());

 

//A_005: Show the Queue Content.

DisplayContent("Queue", Q );

 

//A_006: Remove the First two element from the Queue. Note: The first two entries added will be removed

Console.WriteLine("First Removed Element: {0}" , Q.Dequeue());

Console.WriteLine("Second Removed Element: {0}" , Q.Dequeue());

 

//A_007: Show the Queue Content

DisplayContent("Queue", Q );

 

Pic01.JPG

 

Using Stack Class - Built-in

 

The code you saw above is copy pasted from Queue and changed for Stack. When you add an element it will be added in the Front or Top (Based on how you imagine it. horizontal or vertical). When you remove an item it will be removed from the Front. Hence, the item added last is removed first. The following code demonstrates the usage of Stack:

 

//===============> B. Stack  <==================

Console.WriteLine("===============> B. Stack  <==================");

//B_001: Create a Stack and populate it.

Stack S = new Stack();

 

//B_002: populate 5 Integers to it. Push adds an element to the Stack at the front that is top

for (int i=0; i<5; i++)

            S.Push(i+1);

 

//B_003: Show the Stack Content

DisplayContent("Stack", S );

 

//B_004: Return the Object at the begining of the Stack

Console.WriteLine("First element: {0}", S.Peek());

 

//B_005: Show the Stack Content.

DisplayContent("Stack", S );

 

//B_006: Remove the First two element from the Stack. Note: The Last two entries added will be removed

Console.WriteLine("First Removed Element: {0}" , S.Pop());

Console.WriteLine("Second Removed Element: {0}" , S.Pop());

 

//B_007: Show the Queue Content

DisplayContent("Stack", S );

 

Pic02.JPG


Pictorial representation of Stack and Queue used in this Example
 

Pic03.JPG

 

Note: The sample is created in older version (Dot.net 2003) so that every one can use it. When you open it in higher versions, say yes to covert the solution. 



Login to add your contents and source code to this article
share this article :
post comment
 

Thank you....

Posted by code one Sep 20, 2011

You need eleven timer. Two random function. 10 Timer for Each Counter. One for Incoming.********Among the two function 1 will generate the random number for which Queue (Cashier counter) among the 10 to Pick. Other one will generate the Random number for Number of items (<20) in the basket.**********Now Inside the timer for Incoming queue, call the random function to select the cashier, add the incoming customer to the Counter.*********Inside the timer(Runs for 2 secs initially, after first call, new interval is set, based items in the basket) for each counter, Call the Second Random (Number of Items) function, and set the timer for next tick to 2 * Random return.****** On each counter timer function, your first piece of code should remove the persons when queue is not empty. ***** Hope You got it

Posted by Sivaraman Dhamodaran Sep 18, 2011

thanks

Posted by code one Sep 18, 2011

thanks

Posted by code one Sep 18, 2011
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor