You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对已按letterCount排序的链表同长度段按timesUsed排序?

解决链表同letterCount子段按timesUsed排序的问题

嘿,我看你已经成功定位到letterCount相同的子链表段了,就差临门一脚给这些子段做排序对吧?咱们来把这个问题搞定!

你当前的代码已经能找到连续相同letterCount的节点组,但缺少实际的排序逻辑。针对链表的局部子段,用冒泡排序来实现会比较直观——毕竟咱们只需要在小范围内调整顺序,冒泡排序逻辑简单,容易和现有遍历逻辑结合。

修改后的完整排序函数

void LinkedList::sort() {
    Node* current = head;
    // 遍历整个链表,逐个处理每个letterCount相同的子段
    while (current != nullptr) {
        // 先找到当前子段的末尾节点
        Node* segmentEnd = current;
        while (segmentEnd->next != nullptr && segmentEnd->letterCount == segmentEnd->next->letterCount) {
            segmentEnd = segmentEnd->next;
        }

        // 对当前子段(current到segmentEnd)按timesUsed排序(这里是降序,可按需调整)
        bool swapped;
        do {
            swapped = false;
            Node* temp = current;
            while (temp != segmentEnd) {
                // 这里是降序逻辑:如果前一个节点的timesUsed比后一个小,就交换数据
                // 要是需要升序,把条件改成 temp->timesUsed > temp->next->timesUsed 即可
                if (temp->timesUsed < temp->next->timesUsed) {
                    // 直接交换两个节点的所有数据(比调整链表指针更简单)
                    swap(temp->word, temp->next->word);
                    swap(temp->letterCount, temp->next->letterCount);
                    swap(temp->timesUsed, temp->next->timesUsed);
                    swapped = true;
                }
                temp = temp->next;
            }
        } while (swapped);

        // 跳到下一个letterCount不同的子段开头
        current = segmentEnd->next;
    }
}

代码逻辑说明

  1. 定位子段:外层循环先找到每个letterCount相同的子段的起始(current)和结束(segmentEnd)节点,确保我们只在相同letterCount的范围内排序。
  2. 子段内冒泡排序:在每个子段里,重复遍历相邻节点,比较它们的timesUsed,如果顺序不符合要求就交换节点的数据(直接交换数据比调整链表指针更省心,尤其是针对局部小链表)。
  3. 处理下一个子段:当前子段排序完成后,把current移到下一个不同letterCount的子段开头,继续循环处理。

小提示

  • 如果需要按timesUsed升序排列,只需要把排序条件里的<改成>就行。
  • 因为你的插入函数已经按letterCount排好序了,这个排序函数只会调整同组内的顺序,不会破坏原有的letterCount排序结构。

内容的提问来源于stack exchange,提问作者Julian Shalaby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:17:40