我正在阅读关于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