您要删除列表的开头并使其成为新的结尾。您应该想出如何做到这一点,而代码将是对此的逻辑表示。
- 删除列表的标题。新的头成为下一个项目。
- 现在,被移走的物品独自站立。没事了
- 将节点放在列表的末尾。新尾将成为该节点。
如您所见,您的代码现在并没有完全做到这一点。一次完成一个步骤:
因此,步骤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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)