2016-11-08 3 views
-1

iは、コンパイラが無限ループに入り、私はコードリンクされたリストのソート方法私はこのコードを使用する場合

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

    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; 
} 

にソートするために、挿入コードを変更するように求めてきたすべてのことをしないリンクリスト 仕分けで問題が発生しましたしかし、それは私がそれを持っているので、それはとても悪い外観です

これはリンクリストをソートする必要があります...私は思う!

public void sort() { 
    Node currentNode = head; 
    Node nextNode = head.next; 
    while (nextNode != null) { 
     if(currentNode.num>currentNode.next.num){ 
      Node tmpNode=currentNode; 
      currentNode.num=currentNode.next.num; 
      currentNode.next.num=tmpNode.num; 
     } 
    } 
} 
+1

でnullになります最初のシナリオを検討していませんでした。しかし、たとえあなたがそれをしても、それでもリストを並べ替えることはできません。それはちょうど無限ループを取り除くだろう。 – Keiwan

+0

あなたが持っているのは、コードスニペットのポストです。理解の助けを求める場合は、どこにいらっしゃるのかをよりよく理解する必要があります。コードが何をしていると考えているかを表現するいくつかの個人用の注釈(コードコメントなど)を追加すると、人々は思考の間違いを理解し、それに応じて助けてくれるでしょう。 – Kache

+0

ソート方法*への '挿入 'の変更はどういう意味ですか?それらは2つの全く異なるものです。また、insert関数は既にソートされたリストを保持します。 ( '' head == null''を単に傍注としてチェックするのではありません)。 – Keiwan

答えて

0

リンクリストを挿入中にソートするとします。あなたがそれをソートするために別の関数を必要としないように。あなたは頭だけそれはあなたがループ内で `nextNode`を設定することはありませんしているエラー

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; 
} 
関連する問題