为了账号安全,请及时绑定邮箱和手机立即绑定

如何将链表附加到另一个链表的末尾?

如何将链表附加到另一个链表的末尾?

交互式爱情 2022-07-06 18:20:33
我正在尝试将两个链接列表连接在一起,其中第二个列表将紧跟在第一个列表的尾部之后。在我的追加方法中,我想获取要连接在一起的两个列表,然后将最后一个列表连接到末尾。我无法将当前位置分配给第二个列表的头部。关于我的下一步是什么有什么建议吗?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 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

while (list1 != null) {
    current = current.next;}

list1未更改,您将完成取消引用 NULL 指针

奇怪的是,您在参数中获得了两个列表,而操作不是静态的并且不返回结果。

对我来说,如果不是静态的,则操作必须接收一个列表并将其附加到当前(this)列表的末尾,在参数中迭代列表并使用insertLast添加每个元素

您还可以按值接收参数,最好使用引用而不是白白复制它/它们


查看完整回答
反对 回复 2022-07-06
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

在 append() 方法中:


Link current = first;

while(current.next != null) {

    current = current.next;

}

current.next = list2.first;

当您的当前节点到达最后一个节点时,.next它将为空。那是您加入第二个列表的时候。


查看完整回答
反对 回复 2022-07-06
  • 2 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号