分享

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

 jnstyle 2016-03-22

问题:

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

分析:

假设每一个node的结构是:

  1. class Node {  
  2.     char value;  
  3.     Node next;  
  4. }  

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

代码如下:

  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. }  

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

  1. public Node reverse(Node current)  
  2.  {  
  3.      if (current == null || current.next == null) return 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:///questions/354875/reversing-a-linked-list-in-java-recursively

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

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



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约