Reversing single linked list in C#

后端 未结 13 663
说谎
说谎 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:38

    In case you want a ready-made efficient implementation, I created an alternative to LinkedList that supports enumeration and reverse operations. https://github.com/NetFabric/NetFabric.DoubleLinkedList

    0 讨论(0)
  • 2020-12-07 17:39
        public class Node<T>
        {
            public T Value { get; set; }
            public Node<T> Next { get; set; }
        } 
    
        public static Node<T> Reverse<T>(Node<T> head)
        {
            Node<T> tail = null;
    
            while(head!=null)
            {
                var node = new Node<T> { Value = head.Value, Next = tail };
                tail = node;
                head = head.Next;
            }
    
            return tail;
        }
    
    0 讨论(0)
  • 2020-12-07 17:39

    The definition of ref is unnecessary because if you make the node as a reference type, it is OK to do:

    public static void Reverse(Node root)
    

    Also, the beauty of the interview question is less consumption of memory and in place reversal. Maybe a recursive way of doing it is also asked.

    0 讨论(0)
  • 2020-12-07 17:40

    Complexity O(n+m). Assuming head is the start node:

    List<Node>Nodes = new List<Node>();
    Node traverse= root;
    while(traverse!=null)
    {      
           Nodes.Add(traverse);
           traverse = traverse.Next;
    
    }
    
    int i = Nodes.Count - 1;     
    root = Nodes[i];
    for(; i>0; i--)
    {
      Nodes[i].Next = Nodes[i-1];
    }
    Nodes[0].Next=null;
    
    0 讨论(0)
  • 2020-12-07 17:41
    public Node ReverseList(Node cur, Node prev)
        {
            if (cur == null) // if list is null
                return cur;
    
            Node n = cur.NextNode;
            cur.NextNode = prev;
            return (n == null) ? cur : ReverseList(n, cur);
        }
    
    0 讨论(0)
  • 2020-12-07 17:43

    Why not just have the head point at the tail, the tail point at the head, and go through the list reversing the direction in which prev points?

    If you're not using a head and a tail, just go through the list reversing the prev relationships, and then make head point at the one that had a null prev when you got to it.

    0 讨论(0)
提交回复
热议问题