源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

如何使用递归和非递归方式反转单向链表

  • 时间:2021-03-31 07:38 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:如何使用递归和非递归方式反转单向链表
[b]问题:[/b] 给一个单向链表,把它从头到尾反转过来。比如: a -> b -> c ->d 反过来就是 d -> c -> b -> a 。 [b]分析: [/b]假设每一个node的结构是:
[u]复制代码[/u] 代码如下:
class Node {  char value;  Node next; }
因为在对链表进行反转的时候,需要更新每一个node的“next”值,但是,在更新 next 的值前,我们需要保存 next 的值,否则我们无法继续。所以,我们需要两个指针分别指向前一个节点和后一个节点,每次做完当前节点“next”值更新后,把两个节点往下移,直到到达最后节点。 [b]代码如下: [/b]
[u]复制代码[/u] 代码如下:
public Node reverse(Node current) {  //initialization  Node previousNode = null;  Node nextNode = null;  while (current != null) {   //save the next node   nextNode = current.next;   //update the value of "next"   current.next = previousNode;   //shift the pointers   previousNode = current;   current = nextNode;     }  return previousNode; }
[b]上面代码使用的是非递归方式,这个问题也可以通过递归的方式解决。[/b]代码如下:
[u]复制代码[/u] 代码如下:
public Node reverse(Node current)  {      if (current == null || current.next == null) return current;      Node nextNode = current.next;      current.next = null;      Node reverseRest = reverse(nextNode);      nextNode.next = current;      return reverseRest;  }
递归的方法其实是非常巧的,它利用递归走到链表的末端,然后再更新每一个node的next 值 (代码倒数第二句)。 在上面的代码中, reverseRest 的值没有改变,为该链表的最后一个node,所以,反转后,我们可以得到新链表的head。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部