请问下这个递归单链表倒叙具体的过程

ooesb 2016-06-02 03:49:42

public Node reverse(Node first)
{
if(first == null) return null;
if(first.next == null) return first;
Node second = first.next;
Node rest = reverse(second);
second.next = first;
first.next = null;
return rest;
}

标红这段代码具体怎么运行到最后的。没看很懂。
是从第N个开始向前面调换位子吗。
Node rest = reverse(second);
像这样
Node rest = reverse(2);
Node rest = reverse(3);

Node rest = reverse(last);
是会从链表最后一个元素开始返回值吗直到第一个吗。
second.next = first;
first.next = null;
return rest;
...全文
153 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ooesb 2016-06-12
  • 打赏
  • 举报
回复
引用 9 楼 u010087908 的回复:
[quote=引用 6 楼 luciferisnotsatan 的回复:] [quote=引用 5 楼 u010087908 的回复:] 你自己实际操作一下不就明白了么? 试一下3个节点的 再试一下5个节点的。
赵老湿把alpha娜教坏了[/quote] 不对么?[/quote] 这是书上的程序,结果应该也不会错呐。可是不懂得为什么每次都要return rest;
ooesb 2016-06-03
  • 打赏
  • 举报
回复
输出结果: 1-->2-->3-->4-->5-->6-->7-->8-->9-->10 10-->9-->8-->7-->6-->5-->4-->3-->2-->1
ooesb 2016-06-03
  • 打赏
  • 举报
回复
测试程序引用chen_yongkai的回答。 public class TestLink { static final class Node { final int value; Node next; public Node(int value) { super(); this.value = value; } public void next(Node node) { this.next = node; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { String s = String.valueOf(value); if (next != null) { s += "-->" + next.toString(); } return s; } } public static void main(String[] args) { int size=10; Node root = new Node(1); Node n = root; for (int i = 2; i <= size; i++) { Node m = new Node(i); n.next = m; n = m; } System.out.println(root); System.out.println(reverse(root)); } public static Node reverse(Node first) { if (first == null) return null; if (first.next == null) return first; Node second = first.next; Node rest = reverse(second); second.next = first; first.next = null; return rest; } }
luciferisnotsatan 2016-06-03
  • 打赏
  • 举报
回复
引用 5 楼 u010087908 的回复:
你自己实际操作一下不就明白了么? 试一下3个节点的 再试一下5个节点的。
赵老湿把alpha娜教坏了
NANU-NANA 2016-06-03
  • 打赏
  • 举报
回复
引用 6 楼 luciferisnotsatan 的回复:
[quote=引用 5 楼 u010087908 的回复:] 你自己实际操作一下不就明白了么? 试一下3个节点的 再试一下5个节点的。
赵老湿把alpha娜教坏了[/quote] 不对么?
NANU-NANA 2016-06-02
  • 打赏
  • 举报
回复
你自己实际操作一下不就明白了么? 试一下3个节点的 再试一下5个节点的。
luciferisnotsatan 2016-06-02
  • 打赏
  • 举报
回复
最后一个时,调用reverse,就进了if(first.next == null) return first;这句 然后Node rest = reverse(second); rest就是最后一个, second.next = first; 这样最后一个的(second)下一个就是倒数第二个(first)。 return rest;返回最后一个 此后就是倒数第二个的next连倒数第三,返回最后一个。最终你就有了个倒转的链表,表头就是一路return回来的rest(原倒数第一)。
姓小名白丶 2016-06-02
  • 打赏
  • 举报
回复
不懂帮顶。。。。。
把分全给哥 2016-06-02
  • 打赏
  • 举报
回复
引用 1 楼 So__Sick 的回复:
什么东西?看不懂!
一定要有耐心
紫菜丶 2016-06-02
  • 打赏
  • 举报
回复
什么东西?看不懂!

703

社区成员

发帖
与我相关
我的任务
社区描述
提出问题
其他 技术论坛(原bbs)
社区管理员
  • community_281
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧