首页 > 解决方案 > 如何使用 Java 中的几行代码将给定的前链接转换为后链接?

问题描述

Before:
       +----+----+
list-->|  1 |  / |
       +----+----+
       +----+----+    +----+----+    +----+----+
list2-> |  2 |  +----> |  3 |  +----> |  4 |  / |
       +----+----+    +----+----+    +----+----+
After:
           +----+----+      +----+----+    +----+----+
list 1---->| 4 |     +----> |  1 |  +----> |  2 |  / |
           +----+----+      +----+----+    +----+----+

          +----+----+ 
List2---->|  3 |  / |
          +----+----+ 

这就是我所拥有的:

list.next = list2.next.next // 4 -> 1
list = list2 // 4 -> 1 -> 4 -> 2 -> 3 -> 4
list2 = list.next.next.next.next // 3
list.next.next.next.next = null // 4 -> 1 -> 4 -> 2

不知道对不对?我无法找出问题所在

标签: javanode.jslinked-list

解决方案


嗨@BetheGirly1 欢迎来到 StackOverflow。我想您是在问如何在 Java 中反转链表。

您可以将链表中的所有元素从列表中弹出并将它们推入堆栈,然后再次将它们弹出(如果您知道列表只会很小,这只会很好)。

否则,您可以使用三个变量遍历您的(单数)链表。一个保存前一个 Node 值,一个保存当前值,一个保存下一个值,然后将 Node 中的下一个值与前一个 Node 切换写入。

我的 Java 有点生疏(您确实将其标记为 Node.js,可能是不小心)。

    // pass in the first node in the LinkedList, normally a LinkedList class knows the head. 
    public void reverse(Node head) {
        Node previous = null;
        Node current = head;
        Node nextNode = null;

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

推荐阅读