2016-11-09 39 views
-2

我有這個鏈表:在Java中對鏈表進行排序的正確方法是什麼?

class Node { 
    Node next; 
    int num; 

    public Node(int val) { 
     num = val; 
     next = null; 
    } 
} 

public class LinkedList { 

    Node head; 

    public LinkedList(int val) { 
     head = new Node(val); 
    } 

    public void append(int val) { 
     Node tmpNode = head; 
     while (tmpNode.next != null) { 
      tmpNode = tmpNode.next; 
     } 
     tmpNode.next = new Node(val); 
    } 
    public void print() { 
     Node tmpNode = head; 
     while (tmpNode != null) { 
      System.out.print(tmpNode.num + " -> "); 
      tmpNode = tmpNode.next; 
     } 
     System.out.print("null"); 
    } 

    public static void main(String[] args) { 
     LinkedList myList = new LinkedList(8); 
     myList.append(7); 
     myList.append(16); 
     myList.print(); 
    } 
} 

,我想知道我應該怎麼排序,這個鏈表?我試圖排序它,但奇怪的數字開始出來,在其他情況下,它什麼都不做,排序什麼都沒有。

+1

歡迎來到Stack Overflow!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –

回答

0

您可以在插入自身時對鏈表進行排序。所以你不需要另外的函數來排序它。您沒有考慮最初的情況,其中頭部將僅爲空,即錯誤是

public void insert(int val) { 
Node currentNode = head; 
Node nextNode = head.next; 

if (head==null) { 
    head = new Node(val); 
    head.next = null; 
    return; 
} 

if (currentNode.num > val) { 
    Node tmpNode = head; 
    head = new Node(val); 
    head.next = tmpNode; 
    return; 
} 

if (nextNode != null && nextNode.num > val) { 
    currentNode.next = new Node(val); 
    currentNode.next.next = nextNode; 
    return; 
} 

while (nextNode != null && nextNode.num < val) { 
    currentNode = nextNode; 
    nextNode = nextNode.next; 
} 

currentNode.next = new Node(val); 
currentNode.next.next = nextNode; 
} 
+0

這不是什麼想要的...我只想要一個沒有插入的排序方法 –

+0

那麼你應該更新問題中的確切要求,以便別人不會與你的問題混淆 – jafarbtech

相關問題