我正在阅读java中的链表,我编写了这段代码,当我运行它时我得到3
作为输出,它应该打印出插入数字的相反顺序如下:{{1}我的代码出了什么问题?
10 7 3
由于
答案 0 :(得分:4)
您的insert
方法未将新节点连接到现有列表的最后一个节点。您必须将新节点分配给现有列表的最后一个节点的node.next
:
public void insert(int contents) {
ListNode newNode = new ListNode(contents);
if (head == null) {
head = newNode;
return;
}
ListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
答案 1 :(得分:1)
private ListNode head;
private ListNode tail;
public void insert(int contents) {
ListNode newNode = new ListNode(contents);
if (head == null) {
head = newNode;
tail = newNode;
return;
}
tail.next = newNode;
tail = newNode;
}
为O(1)插入保留尾节点引用。
您的reverse()
方法有点不对:
// this loop will run forever if there are more than 1 nodes
while (nodeNext != null) {
current.next = null;
nodeNext.next = current; // you lose the reference to the entire list here
current = nodeNext;
}
重写功能:
public void reverse() {
ListNode cursor = head;
ListNode newHead = null;
while (cursor != null) {
ListNode next = cursor.next;
cursor.next = newHead;
newHead = cursor;
cursor = next;
}
head = newHead;
}
执行cursor.next = newHead
,丢失对cursor.next
的原始引用。因此,您需要在临时变量中引用cursor.next
:ListNode next = cursor.next;
打印功能
public void print() {
ListNode cursor = head;
while (cursor != null) {
System.out.println(cursor.contents);
cursor = cursor.next;
}
}