我正在閱讀關於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