【问题标题】:Sorting a linked list of integers?对整数链表进行排序?
【发布时间】:2012-12-25 14:22:25
【问题描述】:

我有一个需要排序的LinkedList(它包含ints),我不知道该怎么做。谁能给我的源代码来排序一个 int 链表?

我尝试了这个我在网上找到的代码,但它不起作用。

    public void sort(LinkedList sortlist)
{
    //Enter loop only if there are elements in list
    boolean swapped = (head != null);

    // Only continue loop if a swap is made
    while (swapped)
    {
        swapped = false;

        // Maintain pointers
        Node curr = head;
        Node next = curr.link;
        Node prev = null;

        // Cannot swap last element with its next
        while (next != null)
        {
            // swap if items in wrong order
            if (curr.data>next.data)
            {
                // notify loop to do one more pass
                swapped = true;

                // swap elements (swapping head in special case
                if (curr == head)
                {
                    head = next;
                    Node temp = next.link;
                    next.link = curr;
                    curr.link = temp;
                    curr = head;
                }
                else
                {
                    prev.link = curr.link;
                    curr.link = next.link;
                    next.link = curr;
                    curr = next;
                }
            }

            // move to next element
            prev = curr;
            curr = curr.link;
            next = curr.link;
        }
    }
}

【问题讨论】:

    标签: algorithm sorting data-structures linked-list


    【解决方案1】:

    斯坦福的 CS106B 课程有一个C++ implementation of merge sort on linked lists given in this handout。运行时间为 O(n log n),相当不错。

    如需了解其他方法,请查看this older SO answer,了解如何对链表进行排序。那里没有代码,但是很好地描述了如何将现有想法应用于链表。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      合并排序和快速排序可用于对链接列表进行排序(平均 O(n.long))。此外,如果您的数字是整数,则有一种基数排序的变体,它可以工作 O(n) 并且它已经到位。所以你不满足将链表转换为数组。

      以下是 STL 中的实现信息:http://www.cplusplus.com/reference/list/list/sort/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-04
        • 1970-01-01
        • 2010-10-20
        • 2012-04-09
        • 2022-01-18
        • 2012-10-24
        相关资源
        最近更新 更多