C++按升序对链表进行排序

C++ sort linked list in ascending order

本文关键字:排序 链表 升序 C++      更新时间:2023-10-16

这是我的代码。我想知道为什么它不起作用。

sll_node *sortList(sll_node *head)
{
 int temp=head->value;
 if(head!=NULL||temp>head->next->value)
 {
     head->value=head->next->value;
     head->next->value=temp;
 }
 else
 {
    sortList(head->next);
    sortList(head->next->next);
    sortList(head->next);
 }        
  return head;
}

您展示的代码中的主要问题是您在知道指针是否有效之前就使用了指针。

因此,在将 temp 分配给 head-> 值或使用 head->next 之前,必须确保 head 不等于 NULL。在使用 head->next-> 值或 head->next-next> 之前,必须确保 head->next 不等于 NULL。

试试这个:

sll_node *sortList(sll_node *head)
{
    if(head != NULL)
    {
        int temp=head->value;
        if (head->next != NULL)
        {
            if (temp > head->next->value)
            {
                head->value=head->next->value;
                head->next->value=temp;
            }
            else
            {
                sortList(head->next);
            }
        }
    }
    return head;
}    

运行此程序后,您会遇到另一个问题。

如果您的列表是:[3, 2, 1, 4]
第一次传递排序列表将产生:[2, 3, 1, 4]
第二遍将产生:[2, 1, 3, 4]
第三遍也是最后一遍将产生:[2, 1, 3, 4]

我会让你尝试解决下一步。如果你有具体的问题,一旦你付出更多的努力,我会回答它们。