java - 如何使用 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
不知道对不对?我无法找出问题所在
解决方案
嗨@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;
}
}
推荐阅读
- knockout.js - Dynamic Add New Row Using knockout js
- node.js - 在 NestJS 中为 Pug 设置“basedir”选项
- docker - 如何在 dockerfile 中使用 .ENV 文件中的变量?
- c - printf("%d","%u","%p",ptr,ptr,ptr) 和 printf("%d %u %p",ptr,ptr,ptr) 有什么区别?
- http - 如何查看单击 HTML 按钮时发出的 POST 请求的地址?
- postgresql - 几何类型从数据库中读取为字符串
- swift - 为信用卡输入格式化 NSTextField,例如 (xxxx xxxx xxxx xxxx) [macOS Swift]
- sqlite - 在 SQLite 中使用过滤器和分页查询多对多关系
- php - 致命错误:未捕获的 PDOException:使用 Google Cloud SQL 实例连接
- c# - 如何将标准 DayOfWeek 与 Flag 进行比较