C++ 链表泡泡排序不太正确

C++ 链表泡泡排序不太正确,c++,linked-list,bubble-sort,singly-linked-list,C++,Linked List,Bubble Sort,Singly Linked List,我正在研究链表的bubblesort算法。它在移动数据,但没有正确地对数据进行排序。现在我只担心INT的链接列表。问题在哪里?非常感谢 void List::linkedListBubbleSort() { bool swap = true; Node * temp = firstNode; Node * current; if(firstNode == 0) { cout << "List is empty." &l

我正在研究链表的bubblesort算法。它在移动数据,但没有正确地对数据进行排序。现在我只担心INT的链接列表。问题在哪里?非常感谢

void List::linkedListBubbleSort()
{
    bool swap = true;
    Node * temp = firstNode;
    Node * current;

     if(firstNode == 0)
     {
          cout << "List is empty." << endl;
          return;
     }

     else
     {
         while(swap == true)
         {
             for(current = firstNode; current != NULL && current->next != NULL; current = current->next)
             {
                 if(current->data > current->next->data)
                 {
                     swap = true;
                     temp->data = current->data;
                     current->data = current->next->data;
                     current->next->data = temp->data;
                 }
             else
             swap = false;
             }

         }
void List::linkedListBubbleSort()
{
布尔交换=真;
Node*temp=firstNode;
节点*电流;
if(firstNode==0)
{
(下一步)
{
如果(当前->数据>当前->下一步->数据)
{
swap=true;
温度->数据=当前->数据;
当前->数据=当前->下一步->数据;
当前->下一步->数据=临时->数据;
}
其他的
交换=假;
}
}
您不必使用while(swap==true),因为如果(当前->数据->当前->下一步->数据)返回false,那么您的上循环while(swap==true)将不允许您进一步迭代

    else
    {
         for(current = firstNode; current != NULL && current->next != NULL; current = current->next)
         {
             if(current->data > current->next->data)
             {
                 temp->data = current->data;
                 current->data = current->next->data;
                 current->next->data = temp->data;
             }

         }

     }
  • 您使用指向第一个节点的temp。因此,在交换时,您会损坏数据。 2.当您在第一次交换时停止,您只需要在完成时停止,以通过整个列表,并且没有进行交换
  • 算法不正确。它应该是两个循环…搜索冒泡排序

  • 我不会将指针与0进行对比。
    nullptr
    可能比NULL更好。您不能将现有节点用作交换的临时持有者。@n.m.我应该将当前->数据存储在int中吗?是的,试试看。另外,
    else swap=false
    也不正确,您应该在内部循环之前执行
    swap=false
    。这就是我得到的答案t、 谢谢。