2013-01-11 82 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/