Sequential sorting of randomized source destination traversal path

Given a randomized source destination traversal path like:
d -> e
a -> b
c -> d
b -> c

write a code to sort it as follows:
a -> b
b -> c
c -> d
d -> e

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            //Initializing source destination sequence
            ht.Add("g", "h");
            ht.Add("i", "j");
            ht.Add("a", "b");
            ht.Add("l", "m");
            ht.Add("n", "o");
            ht.Add("d", "e");
            ht.Add("c", "d");
            ht.Add("j", "k");
            ht.Add("k", "l");
            ht.Add("e", "f");
            ht.Add("h", "i");
            ht.Add("b", "c");
            ht.Add("m", "n");
            ht.Add("f", "g");
            //Retrieving the starting city
            string origin = "";
            foreach (string cityKey in ht.Keys)
            {
                int flag = 0;
                foreach (string cityVal in ht.Values)
                {
                    if (cityKey == cityVal)
                    {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0)
                {
                    origin = cityKey;
                    break;
                }
            }
            //Traverse the hash table using key value link
            while (ht[origin] != null)
            {
                Console.WriteLine(origin + " --> " + ht[origin]);
                origin = (string) ht[origin];
            }
        }
    }
}

Output
=======
a --> b
b --> c
c --> d
d --> e
e --> f
f --> g
g --> h
h --> i
i --> j
j --> k
k --> l
l --> m
m --> n
n --> o
Press any key to continue . . .
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