在通用单链表中合并排序
本文关键字:合并 排序 链表 单链表 | 更新日期: 2023-09-27 18:34:30
在
排序方面遇到了一些麻烦,在调试时,我发现了有趣的事情,在方法合并返回数据是正确的,然后它连接到 MergeSortLL 方法并显示 Head 只有一个节点在那里,而它必须有 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;
}
我能在这里错过什么?
您缺少该方法修改链接并返回新标头,因此旧标头显示较少或零的下一个元素是正常的。
如果你替换这个会更明显
return Merge(MergeSortLL(Head), MergeSortLL(half));
跟
Head = Merge(MergeSortLL(Head), MergeSortLL(half));
return Head;
也不要忘记在外部调用中执行相同的操作,例如
LinkedListNode<int> head = ...;
head = MergeSortLL(head);