Javaでリンクリストを読んでいましたが、このコードをプログラムしました。3
を出力すると、挿入された数字の逆順が次のように出力されます:10 7 3
..私のコードに何が間違っていますか?Javaでリンクリストを実装
public class List {
private class ListNode {
private int contents;
private ListNode next;
ListNode(int contents) {
this.contents = contents;
this.next = null;
}
}
private ListNode head;
public List() {
head = null;
}
public void insert(int contents) {
ListNode newNode = new ListNode(contents);
if (head == null) {
head = newNode;
}
ListNode current = head;
while (current != null) {
current = current.next;
}
current = newNode;
}
public void reverse() {
ListNode current = head;
ListNode nodeNext = current.next;
while (nodeNext != null) {
current.next = null;
nodeNext.next = current;
current = nodeNext;
}
head = current;
}
public String toString() {
String s = "";
ListNode current = head;
while (current != null) {
s = current.contents + s;
current = current.next;
}
return s;
}
public static void main(String[] args) {
List l = new List();
l.insert(3);
l.insert(7);
l.insert(10);
l.reverse();
System.out.println(l.toString());
}
}
おかげ
値を挿入するときに、あなたが 'next'を設定することはありません。デバッガを使用すると、すぐにそのことが分かりました。 – jhamon
あなたはこれをどういう意味ですか? 'public void insert(int contents、ListNode next){' –
どうやってこれを計画しましたか?あなたはあなたが心に持っていたことを書いたのですか、それとも最初に紙でそれをしましたか? – AxelH