合并通用单链表中的排序

时间:2016-02-14 17:49:27

标签: c# generics linked-list mergesort

在排序时遇到一些麻烦,在调试时,我发现有趣的是在方法合并中返回数据是正确的,然后它加入到MergeSortLL方法并显示 Head < / strong>只有一个节点,而它必须有ex。 5个排序节点。我能错过什么?

public static LinkedListNode<T> MergeSortLL<T>(LinkedListNode<T> Head) where T : IComparable<T>
{           
    if (Head == null || Head.Next == null)
        return Head;

    LinkedListNode<T> middle = GetMiddle(Head);
    LinkedListNode<T> half = middle.Next;
    middle.Next = null;

    return Merge(MergeSortLL(Head), MergeSortLL(half));
}

            public static LinkedListNode<T> Merge<T>(LinkedListNode<T> Left, LinkedListNode<T> Right) where T : IComparable<T>
            {

                var mHead = new LinkedListNode<T>(default(T));
                LinkedListNode<T> curr = mHead;

                while (Left != null && Right != null)
                {
                    if (Left.Value.CompareTo(Right.Value) <= 0)
                    {
                        curr.Next = Left;
                        Left = Left.Next;
                    }
                    else
                    {
                        curr.Next = Right;
                        Right = Right.Next;
                    }
                    curr = curr.Next;
                }
                curr.Next = (Left == null) ? Right : Left;

                return mHead.Next;
            }

            public static LinkedListNode<T> GetMiddle<T>(LinkedListNode<T> Head) where T : IComparable<T>
            {
                if (Head == null)
                {
                    return Head;
                }

                LinkedListNode<T> slow, fast;
                slow = fast = Head;

                while (fast.Next != null && fast.Next.Next != null)
                {
                    slow = slow.Next;
                    fast = fast.Next.Next;
                }
                return slow;
            }

1 个答案:

答案 0 :(得分:1)

  

我在这里可以错过什么?

您错过了该方法修改了链接并返回头部,因此旧头部显示较少或零下一个元素是正常的。

如果你替换这个

会更明显
return Merge(MergeSortLL(Head), MergeSortLL(half));

Head = Merge(MergeSortLL(Head), MergeSortLL(half));
return Head;

另外,不要忘记在外部呼叫中也这样做,例如

LinkedListNode<int> head = ...;
head = MergeSortLL(head);