【发布时间】:2018-01-06 22:22:03
【问题描述】:
我正在尝试反转一个链表并返回新的头部。
public Node reverse(Node head) {
Node node = head;
if (node.next == null) {
head = node;
return head;
}
Node next = node.next;
reverse(next);
next.next = node;
return head;
}
节点类:
public class Node {
int data;
Node next;
}
输入 1 -> 2 -> 3 -> 4 -> 5 我得到输出 1 -> 2 -> 1 -> 2 -> 1。为什么它会循环通过前 2 个节点而忽略剩余的 3 ?还有,为什么新的head没有更新到节点5?
【问题讨论】:
-
请take the tour 了解该网站的运作方式以及此处的主题有哪些问题,并edit 相应地提出您的问题。另见:How to Debug Small Programs
-
我认为,如果您将列表推入堆栈,然后从堆栈的头部创建一个新列表(或清除旧列表),它也会反转该列表。可能不节省空间,但易于编码和维护。
标签: java linked-list