Queue Implementation Using Array

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication2

{

    class Program

    {

        public class ArrayQueue

        {

 

            protected object[] data;

            protected int start, end;

 

            public ArrayQueue(int capacity)

            {

                data = new object[capacity + 1];

                start = end = 0;

            }

 

            public bool IsEmpty()

            {

                return start == end;

            }

 

            public void Insert(object o)

            {

                int n = (start + 1) % data.Length;

                if (n != end)

                    data[start = n] = o;

            }

 

            public object Remove()

            {

 

                if (IsEmpty())

                    return null;

                end = (end + 1) % data.Length;

                object o = data[end];

                data[end] = null;

                return o;

            }

        }

 

        static void Main(string[] args)

        {

            ArrayQueue aQueue = new ArrayQueue(10);

 

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

            {

                string objToQueue = "obj" + i;

                // Display what we’re doing

                Console.WriteLine("Inserting: {0}", objToQueue);

                // Insert object onto the queue

                aQueue.Insert(objToQueue);

            }

            Console.WriteLine("****************");

            // Remove all elements from the queue

            while (!aQueue.IsEmpty())

            {

                // Remove object from the queue

                string objFromQueue = (string)aQueue.Remove();

 

                // Display what we’re doing

                Console.WriteLine("Removed: {0}", objFromQueue);

            }

        }

    }

}
 
Inserting: obj0
Inserting: obj1
Inserting: obj2
Inserting: obj3
Inserting: obj4
Inserting: obj5
Inserting: obj6
Inserting: obj7
Inserting: obj8
Inserting: obj9
****************
Removed: obj0
Removed: obj1
Removed: obj2
Removed: obj3
Removed: obj4
Removed: obj5
Removed: obj6
Removed: obj7
Removed: obj8
Removed: obj9
Press any key to continue . . .

 

Upon insertion, add one to start and mod, and upon removal, add one to end and mod. The end always follows the start.

http://www.theparticle.com/csdata.html#Array_Stack

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s