在双链表中搜索c#

时间:2016-09-13 02:32:36

标签: c# search doubly-linked-list

我正在编写一个使用双向链表的应用程序。我需要在此列表中实现搜索。有一个名称,ID,部门的员工列表。我需要做的是通过她/他的姓氏找到指定的员工。任何想法,如何实施?

4 个答案:

答案 0 :(得分:4)

请不要重新发明轮子。所有类都已经在.Net中 - 只需初始化LinkedList并使用Enumerable.FirstOrDefault进行搜索:

  LinkedList<Employee> employees = ....
  var firstWithIdSeven =  employees.FirstOrDefault(e => e.Id == 7); // assuming id is int

请注意,如果您需要使用Dictionary使用自定义比较器对某些参数子集进行频繁搜索,效率会更高。

答案 1 :(得分:1)

如果这是针对实际的C#代码,您应该使用系统附带的集合(例如LinkedList)。

出于教育目的,算法如下:

def find(lastName):
    set curr to head
    while curr <> null:
        if curr.lastName == lastName:
            return curr
        curr = curr.next
    return null

将其翻译成C#(或任何其他程序语言)应该相对容易。

答案 2 :(得分:1)

Trolling level 7:递归lambda

如果您正在寻找异国情调的实现 - 请查看High Level Function Confusion with Lambda/LINQ expressions in C#,其中讨论了使用递归lambda表达式的迭代。

所以假设你的节点是

 class Employee
 {
     // code to initialize omitted
     public Employee Next { get;}
     public int Id { get;}
 }

现在我们可以使用以下递归lambda(转换为匿名递归lambda是读者练习)

Func<
    Func<Employee, bool>,     // condition to continue iteration
    Func<Employee, Employee>, // "next" function
    Func<Employee, Employee>  // resulting iterator method
    > Loop = null;
Loop = (c , f ) => n => c(n) ? Loop(c , f ) ( f (n)): n;
Func<Employee, Employee> findIdSevenStartingFrom = Loop(
       n => !(n == null || n.Id == 7), // condition to continue search
       n => n.Next );                  // iterator function 

现在使用findIdSevenStartingFrom我们可以传递列表中的任何元素并搜索到结尾以通过Id找到它。

var listHead = new Employee{ Id = 6, Next = new Employee { Id = 7 } };
var item = findIdSevenStartingFrom(listHead);

答案 3 :(得分:0)

我认为你正在寻找这样的东西:

员工:

public class Employee
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

双重链接节点:

public class DoubleLinkedList
{
    public Employee Employee {get; set;}
    public DoubleLinkedList Next {get; set;}
    public DoubleLinkedList Prev {get; set;}
}

在列表中按名称查找员工的功能:

public Employee FindByName(DoubleLinkedList startNode, string name)
{
    var currentNode = startNode;
    while(currentNode != null)
    {
        if(currentNode.Employee.LastName == name) 
        {
            return currentNode.Employee; // Found
        }
        currentNode = currentNode.Next;
    }
    return null; // Not found
}