我正在嘗試將兩個鏈接列表連接在一起,其中第二個列表將緊跟在第一個列表的尾部之后。在我的追加方法中,我想獲取要連接在一起的兩個列表,然后將最后一個列表連接到末尾。我無法將當前位置分配給第二個列表的頭部。關于我的下一步是什么有什么建議嗎?public class Link {public long dData; // data itempublic Link next; // next link in list// -------------------------------------------------------------public Link(long d) // constructor{ dData = d;}// -------------------------------------------------------------public void displayLink() // display this link{ System.out.print(dData + " ");}// -------------------------------------------------------------} // end class Linkpublic class FirstLastList {private Link first; // ref to first linkprivate Link last; // ref to last link// -------------------------------------------------------------public FirstLastList() // constructor{ first = null; // no links on list yet last = null;}// -------------------------------------------------------------public boolean isEmpty() // true if no links{ return first == null;}// -------------------------------------------------------------public void insertFirst(long dd) // insert at front of list{ Link newLink = new Link(dd); // make new link if (isEmpty()) // if empty list, { last = newLink; // newLink <-- last } newLink.next = first; // newLink --> old first first = newLink; // first --> newLink}// -------------------------------------------------------------public void insertLast(long dd) // insert at end of list{ Link newLink = new Link(dd); // make new link if (isEmpty()) // if empty list, { first = newLink; // first --> newLink } else { last.next = newLink; // old last --> newLink } last = newLink; // newLink <-- last}
2 回答

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
在
while (list1 != null) {
current = current.next;
}
list1未更改,您將完成取消引用 NULL 指針
奇怪的是,您在參數中獲得了兩個列表,而操作不是靜態的并且不返回結果。
對我來說,如果不是靜態的,則操作必須接收一個列表并將其附加到當前(this)列表的末尾,在參數中迭代列表并使用insertLast添加每個元素
您還可以按值接收參數,最好使用引用而不是白白復制它/它們

qq_花開花謝_0
TA貢獻1835條經驗 獲得超7個贊
在 append() 方法中:
Link current = first;
while(current.next != null) {
current = current.next;
}
current.next = list2.first;
當您的當前節點到達最后一個節點時,.next它將為空。那是您加入第二個列表的時候。
添加回答
舉報
0/150
提交
取消