2016-04-02 17 views
1

我一直在努力完成我的任务,但我不知道如何创建一个链接列表与多个分支。我已经提取了我的数据,将其缩小并存储在列表中。C#与多个分支的链接列表

List<Route> routes = new List<Route>(); 

路由包含两个字符串变量:city1Namecity2Name

Route route = new Route("FirstCity", "SecondCity"); 

这意味着有FirstCitySecondCity之间的路由。每个城市可以有多条路线到其他城市。

有人可以告诉我如何将这些数据存储在链表中吗? 我明白什么是链接列表,我想我可以使用foreach之后获取多个可能的路由数据,但是我无法为此编写算法。 :(

+0

你正在寻找一个节点图https://msdn.microsoft。 com/en-us/library/ms379574(v = vs.80).aspx – InferOn

+0

@Osvaldon在下面看到我的回答,我已经添加了一个片段以查找从一个城市到其他城市的可能路线。但是这并没有找到最短路径。在此处查看演示https://repl.it/CBgX/3 –

回答

4

您可以使用List<T>.Add追加T类型的任何物品,而T可以是任何.NET兼容的数据类型。在你的情况TRoute。所以,你可以添加,可以是隐式转换为Route

任何值
routes.Add(route); 

此外,在.NET中List<T>是不是一个链接列表。List<T> is implemented using Array internally。在.NET链接列表实现LinkList<T>

编辑

这里是一个非常简单的实现,以查找其他城市的路径。

static bool TryFindPath(List<Route> routes, string from, string to, int maxDepth) { 

    if (maxDepth <= 0) // To prevent StackOverFlowException 
     return false; 

    // Find all the routes with starting point == `from` 
    var startingPoints = Routes.Where(r => r.From == from).ToArray(); 
    if (startingPoints.Length == 0) // No such route exists 
     return false; 

    // See if any of route directly leads to `to` 
    var matchingRoute = startingPoints.Where(r => r.To == to).FirstOrDefault(); 
    if (matchingRoute != null) { 
     routes.Add(matchingRoute); // If so, we found that 
     return true; 
    } 


    // We are stepping into next level, decrease maxDepth by one 
    maxDepth -= 1; 

    // Otherwise iterate through all starting points and find path from 
    // that specific city refered by to our destination 
    foreach (var route in startingPoints) { 

     // Clone `routes` 
     var thisRoutes = new List<Route>(routes); 
     thisRoutes.Add(route); 

     if (TryFindPath(thisRoutes, route.To, to, maxDepth)) { 

      // Copy all newly added routes in `thisRoutes` to original `routes` 
      for (var i = routes.Count; i < thisRoutes.Count; i++) { 
       routes.Add(thisRoutes[i]); 
      } 

      return true; 
     } 
    } 

    return false; 
} 

我假设Route类的定义如下

class Route { 

    public string From { get; set; } 
    public string To { get; set; } 

    public Route(string from, string to) { 
     From = from; 
     To = to; 
    } 
} 

你可以找到工作演示here

+0

我很感谢您所做的工作,我会为您添加声誉。但我真正需要的是从存储在数组中的数据创建一个多路链表List routes = new List ();因为这是分配的主要要求:(我将添加一个单向链表的样子,或者我被告知的例子。 – Osvaldon

0
List<Route> routes = new List<Route>(); 
Route route = new Route("FirstCity", "SecondCity"); 
routes.Add(route); 

foreach (oneRoute in routes) 
{ 
    // The other work you're interested in doing 
    // oneRoute represents each single route one at a time. 
}