2013-01-11 80 views
-2

我有一个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; 
     } 
    } 
} 

回答

0

合并排序和快速排序可用于对llink-lists(平均O(n.long))进行排序。另外,如果你的数字是整数,则有一个基数分类的变化,它工作在O(n)并且它已经到位。所以你不会将链接列表转换为数组。

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