排序整数的链表?

时间:2013-01-11 02:34:58

标签: algorithm sorting data-structures linked-list

我有LinkedList需要排序(它包含int s),我不知道该怎么做。任何人都可以给我的源代码来排序一个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;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

斯坦福大学的CS106B课程有C++ implementation of merge sort on linked lists given in this handout。它在时间O(n log n)运行,这是非常好的。

有关其他方法的调查,请查看this older SO answer有关如何对链接列表进行排序的信息。那里没有代码,但是很好地描述了如何使现有的想法适用于链表。

希望这有帮助!

答案 1 :(得分:0)

合并排序和快速排序可用于对llink-lists(平均O(n.long))进行排序。此外,如果你的数字是整数,那么有一个基数排序的变体,它起作用O(n)并且它就位。所以你不能满足将链接列表转换为数组。

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