2016-11-09 4 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

ようこそ!デバッガの使い方を学ぶ必要があるようです。 [補完的なデバッグ手法](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)にご協力ください。その後も問題が残っている場合は、もう少し詳しくお聞かせください。 –

答えて

0

リンクリストを挿入中に並べ替えることができます。あなたがそれをソートするために別の関数を必要としないように。先頭のシナリオを考慮しなかったのは、エラーが発生したヘッドだけがNULLになる場合です。

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

関連する問題