[英]implementation of a linked list in java
我正在閱讀有關Java中鏈表的信息,我已對此代碼進行了編程,運行它時,我得到3
作為輸出,它應該按如下所示打印出插入數字的相反順序: 10 7 3
..我的代碼有什么問題?
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());
}
}
謝謝
您的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;
}
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.