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

问题:

给一个单向链表,把它从头到尾反转过来。比如: a -> b -> c ->d 反过来就是 d -> c -> b -> a 。

分析:

假设每一个node的结构是:

[java]  view plain  copy
  1. class Node {  
  2.     char value;  
  3.     Node next;  
  4. }  

因为在对链表进行反转的时候,需要更新每一个node的“next”值,但是,在更新 next 的值前,我们需要保存 next 的值,否则我们无法继续。所以,我们需要两个指针分别指向前一个节点和后一个节点,每次做完当前节点“next”值更新后,把两个节点往下移,直到到达最后节点。

代码如下:

[java]  view plain  copy
  1. public Node reverse(Node current) {  
  2.     //initialization  
  3.     Node previousNode = null;  
  4.     Node nextNode = null;  
  5.       
  6.     while (current != null) {  
  7.         //save the next node  
  8.         nextNode = current.next;  
  9.         //update the value of "next"  
  10.         current.next = previousNode;  
  11.         //shift the pointers  
  12.         previousNode = current;  
  13.         current = nextNode;           
  14.     }  
  15.     return previousNode;  
  16. }  

上面代码使用的是非递归方式,这个问题也可以通过递归的方式解决。代码如下:

[java]  view plain  copy
  1. public Node reverse(Node current)  
  2.  {  
  3.      if (current == null || current.next == nullreturn current;  
  4.      Node nextNode = current.next;  
  5.      current.next = null;  
  6.      Node reverseRest = reverse(nextNode);  
  7.      nextNode.next = current;  
  8.      return reverseRest;  
  9.  }  
递归的方法其实是非常巧的,它利用递归走到链表的末端,然后再更新每一个node的next 值 (代码倒数第二句)。 在上面的代码中, reverseRest 的值没有改变,为该链表的最后一个node,所以,反转后,我们可以得到新链表的head。

参考:
http://stackoverflow.com/questions/354875/reversing-a-linked-list-in-java-recursively

http://blog.csdn.net/beiyeqingteng/article/details/7030020

转载请注明出处:http://blog.csdn.net/beiyetengqing

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值