【问题标题】:bubble sort linked list not sorting冒泡排序链表不排序
【发布时间】:2014-11-15 21:46:54
【问题描述】:

为什么我的冒泡排序算法不对链表进行排序? 当给定一个列表并调用该方法时,它将输出相同的列表。我的 for 循环中的当前逻辑有什么问题?

private:
    IntNode *head, *tail;

节点结构:

struct IntNode
{
    int data;
    IntNode * next;
};

冒泡排序法:

void NodeSLList::SortList()
{
    if (head == NULL || head->next == NULL)
        return;

    IntNode * current = head;
    IntNode * nextElement = current->next;
    IntNode * temp = NULL;

    int changed = 1;


    while (changed)
    {
        changed = 0;
        for (current; (current != NULL) && (nextElement = NULL); )
        {
            if (current->data > nextElement->data)
            {
                temp = current->next;
                current->next = nextElement->next;
                nextElement->next = temp;
                changed = 1;
            }
            current = current->next;
            nextElement = nextElement->next;
        }

    }

}

【问题讨论】:

  • 好像是赋值运算符:nextElement = NULL
  • if的内容替换为std::swap(current->data, nextElement->data),即可解决问题。

标签: c++ linked-list logic bubble-sort


【解决方案1】:

问题是由于在for循环中分配而不是比较引起的。

如果你正在实现一个链表,我可以建议使用哨兵,而不是头
和 NULL 作为结束。这会在插入和移除过程中移除所有“极端情况”。
哨兵节点始终存在,不包含数据,指向第一项,
最后一项指向它。

我还建议使用Mergesort,它适用于链表,运行在 O(NlogN) 中,
并且没有空间开销。你可以找到一个实现here

【讨论】:

    【解决方案2】:

    尝试通过调试器运行它。如果你在第二次循环changed 时查看current 的值,你会看到current 仍然是null,所以第二次循环changed 不会通过current 循环。

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2012-07-19
      • 2015-08-20
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多