包含指向下一个的指针的排序结构

Sort struct that contains pointer to the next

本文关键字:排序 结构 指针 包含指 下一个      更新时间:2023-10-16

所以我有这样的东西:

struct Something
{
    int number;
    Something* next;
};
我想

按数字对它们进行排序,虽然我不想更改数字,但我想更改指向下一个的指针。

我该怎么做?

我知道"列表"的结束和开始,(先进先出顺序)

对链表使用 MergeSort:首先使用两个正在运行的指针遍历列表,其中一个指针前进速度慢两倍。当您到达列表末尾时,慢指针指向中间。拆分列表并递归地对两半进行排序,然后合并。

有各种排序算法(http://www.sorting-algorithms.com/),到目前为止,我会在这个例子中使用random|selection算法。它将看起来像这样:

void Something::SortAscending() {
   Something* current = next;
   Something* smallest = next;
   while( current ) {
      if( current->number < smallest->number ) {
         smallest = current;
      }
      current = current->next;
   }
   if( smallest != next )
      smallest->next = next;
   next = smallest;
   next->SortAscending();
}

但是请注意,如果您被赋予列表的头部,则可能不会使用我上面提供的功能类型对其进行更改。

排序 -> 对于排序数组的每个元素更新下一个指针