単一リンク リストの並べ替えメソッドを実装しようとしています。このメソッドは、リストを調べ、ノードのペアを比較し、必要に応じてこれらのいずれかを先頭に配置することを想定しています。他に 2 つのメソッドを使用します: - Remove() (リストから特定のノードを削除します) - InsertFront() (リストの先頭に新しいノードを挿入します。これらのメソッドは両方とも単独で機能し、すべてがコンパイルされます。
public Link remove(String lastName)
{
Link current_ = first_;
Link prior_ = null;
Link found_ = null;
while (current_ != null && current_.lastName.compareTo(lastName) != 0)
{
prior_ = current_;
current_ = current_.next;
}
if(current_ != null)
{
if(prior_ == null)
{
found_ = first_;
System.out.println(current_.next.lastName);
first_ = current_.next;
}
else if(current_ == last_)
{
found_ = last_;
Link hold_ = first_;
first_ = prior_;
first_.next = current_.next;
first_ = hold_;
}
else
{
found_ = current_;
Link hold_ = first_;
first_ = prior_;
first_.next = current_.next;
first_ = hold_;
}
}
return found_;
}
public void insertFront(String f, String m, String l)
{
Link name = new Link(f, m, l);
if (isEmpty())
{
System.out.println("Adding first name");
first_ = name;
last_ = name;
}
else
{
System.out.println("Adding another name");
Link hold_ = first_;
first_ = last_;
first_.next = name;
last_ = first_.next;
first_ = hold_;
}
}
私はそれを修正しようとしましたが、常に2つの異なる問題に遭遇します:
機能しますが、リンクを挿入し直せません。
public void Sort() { Link temp_; boolean swapped_ = true; while (swapped_ == true) { swapped_ = false; Link current_ = first_; String comp_ = current_.lastName; while (current_ != null && current_.lastName.compareTo(comp_) >= 0) { current_ = current_.next; } if (current_ != null) { temp_ = remove(current_.lastName); insertFront(temp_.firstName, temp_.middleName, temp_.lastName); swapped_ = true; } } }
Null ポインター例外が発生します。
Exception in thread "main" java. lang. NullPointerException at List $ Link . access $000(List . java : 25) at List . Sort ( List . java:165) at main( java :79)
Java 結果: 1
デバッグの結果:
Listening on javadebug
Not able to submit breakpoint LineBreakpoint LinearGenericSearch.java : 28, reason: The breakpoint is set outside of any class.
Invalid LineBreakpoint LinearGenericSearch.java : 28
User program running
Debugger stopped on uncompilable source code.
User program finished
public void Sort()
Link temp_;
boolean swapped_ = true;
while (swapped_ == true)
{
Link current_ = first_;
swapped_ = false;
while (current_.next != null)
{
if((current_.lastName.compareTo(current_.next.lastName)) > 0)
{
temp_ = remove(current_.next.lastName);
insertFront(temp_.firstName, temp_.middleName, temp_.lastName);
swapped_ = true;
}
current_ = current_.next;
}
}
}
私の質問は次のとおりです。私は何を間違っていますか? 次回これを回避する方法について何かアドバイスはありますか?