将链表的头部移动到尾部



我需要在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. 删除列表的头部。新头部成为下一项。
  2. 被移除的项目现在是单独存在的;后面什么也没有。
  3. 将节点放置在列表的末尾。新的尾巴成为该节点。
现在你的代码,正如你所看到的,并没有完全做到这一点。一次执行一步:

那么,第一步:

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

然后,步骤2:

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

最后,第三步:

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<E> list){
    if(list.size() < 2)
        return;
    E aux = list.get(0);
    list.remove(0);
    list.add(list.size(),aux);
}

你可以这样做:

LinkedList<E> list = new LinkedList<E>();
list.addLast(list.pop());

最新更新