亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將鏈表附加到另一個鏈表的末尾?

如何將鏈表附加到另一個鏈表的末尾?

牧羊人nacy 2022-07-06 09:58:29
我正在嘗試將兩個鏈接列表連接在一起,其中第二個列表將緊跟在第一個列表的尾部之后。在我的追加方法中,我想獲取要連接在一起的兩個列表,然后將最后一個列表連接到末尾。我無法將當前位置分配給第二個列表的頭部。關于我的下一步是什么有什么建議嗎?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添加每個元素


您還可以按值接收參數,最好使用引用而不是白白復制它/它們


查看完整回答
反對 回復 2022-07-06
?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

在 append() 方法中:


Link current = first;

while(current.next != null) {

    current = current.next;

}

current.next = list2.first;

當您的當前節點到達最后一個節點時,.next它將為空。那是您加入第二個列表的時候。


查看完整回答
反對 回復 2022-07-06
  • 2 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號