Reversing single linked list in C#

后端 未结 13 907
说谎
说谎 2020-12-07 17:02

I am trying to reverse a linked list. This is the code I have come up with:

 public static void Reverse(ref Node root)
 {
      Node tmp = root;
      Node n         


        
13条回答
  •  天涯浪人
    2020-12-07 17:37

    Years ago I missed out on a hipster-L.A.-entertainment-company ASP.NET MVC developer position because I could not answer this question :( (It's a way to weed out non-computer-science majors.) So I am embarrassed to admit that it took me way too long to figure this out in LINQpad using the actual LinkedList:

    var linkedList = new LinkedList(new[]{1,2,3,4,5,6,7,8,9,10});
    linkedList.Dump("initial state");
    
    var head = linkedList.First;
    while (head.Next != null)
    {
        var next = head.Next;
        linkedList.Remove(next);
        linkedList.AddFirst(next.Value);
    }
    
    linkedList.Dump("final state");
    

    The read-only LinkedListNode.Next property is what makes LinkedList so important here. (Non-comp-sci people are encouraged to study the history of Data Structures---we are supposed to ask the question, Where does the linked list come from---why does it exist?)

提交回复
热议问题