把链表的头部移到尾部
我需要在Java中编写一个方法,将链表中的第一个元素移动到最后一个位置。
为了实现这一点,我相信我必须设置一个节点来引用头部后面的第一个元素,然后将下一个节点设置为null。 我尝试使用我的方法执行此操作,但在运行该方法时,输出不正确。
我所拥有的其他课程很可能无法在此发布,但我认为我只需要帮助概念化如何将第一个元素移动到列表的末尾。
我写的方法是:
public void moveFirstToEnd() { if (head.next == null) { throw new NoSuchElementException(); } Node node = head.next; node.next = null; head.next = node; tail.next = node; tail = node; }
你想删除列表的头部并使其成为新的尾部。 你应该弄清楚如何在脑海中做到这一点,代码将是一个逻辑表示。
- 删除列表的头部。 新头成为下一个项目。
- 现在,被删除的物品是独立的; 它之后什么也没有。
- 将节点放在列表的末尾。 新尾部成为该节点。
正如您所看到的,您现在的代码并不完全如此。 一次完成一个步骤:
那么,第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 list tail = node; // <- becomes new end of list
或者,如果您想要将其可视化:
Node node = head: +------+ +------+ +------+ +------+ | head |--->| |--->| |--->| tail | +------+ +------+ +------+ +------+ node head = head.next: +------+ +------+ +------+ +------+ | |--->| head |--->| |--->| tail | +------+ +------+ +------+ +------+ node node.next = null: +------+ +------+ +------+ +------+ | | | head |--->| |--->| tail | +------+ +------+ +------+ +------+ node tail.next = node: +------+ +------+ +------+ +------+ | head |--->| |--->| tail |--->| | +------+ +------+ +------+ +------+ node tail = node: +------+ +------+ +------+ +------+ | head |--->| |--->| |--->| tail | +------+ +------+ +------+ +------+ node
顺便说一句,如果您已经定义了popFront
(或其他)和/或append
操作,请不要忘记您也可以使用它们; 没有意义重复代码:
Node node = popFront(); // if you have this append(node); // if you have this
你可以做:
public void moveFirstToLast(LinkedList list){ if(list.size() < 2) return; E aux = list.get(0); list.remove(0); list.add(list.size(),aux); }
你可以做:
LinkedList list = new LinkedList (); list.addLast(list.pop());