zoukankan      html  css  js  c++  java
  • reverse list

    public void reverse (){
    Node end =null,p,q; 
    p=head; //p代表当前节点,end代表翻转后p后面的,q代表翻转前p后面的
    while(p!=null){ //如果当前节点不为空 
    q=p.next; //q赋值为p后面的节点
    p.next=end; //p指向p后面那个
    end=p; //end后移一位
    p=q; //p后移一位
    }
    head=end;
    }
    //上面代码使用的是非递归方式,这个问题也可以通过递归的方式解决。代码如下:
    [java] view plain copy
    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。
  • 相关阅读:
    WebSphere--安全性
    WebSphere--会话跟踪
    WebSphere--用户简要表
    WebSphere--连接管理器
    WebSphere--部署Servlet
    WebSphere--定制配置
    WebSphere--安装与配置
    WebSphere--基本特性
    六、Html头部和元信息
    五、Html表单标签
  • 原文地址:https://www.cnblogs.com/kydnn/p/5192681.html
Copyright © 2011-2022 走看看