栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将链表的头移到尾

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将链表的头移到尾

您要删除列表的开头并使其成为新的结尾。您应该想出如何做到这一点,而代码将是对此的逻辑表示。

  1. 删除列表的标题。新的头成为下一个项目。
  2. 现在,被移走的物品独自站立。没事了
  3. 将节点放在列表的末尾。新尾将成为该节点。

如您所见,您的代码现在并没有完全做到这一点。一次完成一个步骤:

因此,步骤1:

Node node = head;head = head.next; // <- remove head, new head becomes next item

然后,执行步骤2:

node.next = null; // there's nothing after it.

最后,第3步:

tail.next = node; // <- add to end of listtail = node; // <- becomes new end of list

或者,如果您希望将其可视化:

Node node = head:+------+    +------+    +------+    +------+| head |--->|      |--->|      |--->| tail |+------+    +------+    +------+    +------+  nodehead = head.next:+------+    +------+    +------+    +------+|      |--->| head |--->|      |--->| tail |+------+    +------+    +------+    +------+  nodenode.next = null:+------+    +------+    +------+    +------+|      |    | head |--->|      |--->| tail |+------+    +------+    +------+    +------+  nodetail.next = node: +------+    +------+    +------+    +------+ | head |--->|      |--->| tail |--->|      | +------+    +------+    +------+    +------+      nodetail = node: +------+    +------+    +------+    +------+ | head |--->|      |--->|      |--->| tail | +------+    +------+    +------+    +------+      node

顺便说一句,如果您已经碰巧定义了

popFront
(或其他)和/或
append
操作,请不要忘记也可以使用它们。没有意义重复代码:

Node node = popFront(); // if you have thisappend(node); // if you have this


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号