zoukankan      html  css  js  c++  java
  • 单链表翻转

    import java.util.Stack;
    public class Reverse{
        class LNode{
            int data;
            LNode next;
            public LNode(int data){
                this.data=data;
            }
        }
         public static void main(String []args){
            Reverse r = new Reverse();
            for(int i=1;i<=10;i++){
                r.add(i);
            }
            // r.print(r.head);
            r.reverseLink(r.head);
         }
         LNode head;
         LNode current;
         Stack<Integer> s = new Stack<Integer>();
        //通过栈的方式实现
        //  public void reverseLink(LNode node){
        //     current = node;
        //     while(current!=null){
        //         s.push(current.data);
        //         current=current.next;
        //     }
        //     while(!s.empty()){
        //         system.out.println(s.pop());
        //     }
            
        //  }
        
        //递归实现
        public void reverseLink(LNode node){
            if(node!=null){
                if(node.next!=null){
                    reverseLink(node.next);
                }
                System.out.println(node.data);
            }
        }
         public void add(int i){
            if(head==null){
                head=new LNode(i);
                current = head;
            }else{
                current.next=new LNode(i);
                current = current.next;
            }
         }
         public void print(LNode node){
             if(node==null) return;
             current = node;
             while(current!=null){
                System.out.println(current.data);
                current=current.next;
             }
         }
    }

    注:既然想到了用栈来实现这个函数,而递归在本质上就是一个栈结构,于是很自然地又想到了用递归来实现。要实现反过来输出链表,我们每访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了。

  • 相关阅读:
    吃饭吧唧嘴的童鞋看过来
    CUDA 6.5 && VS2013 && Win7:创建CUDA项目
    IDM下载工具
    virgo虚拟桌面
    北方民族大学计算机科学与工程学院研究生导师
    从图片加载纹理-使用glut工具
    OpenGL Vertex Array
    OpenGL顶点缓冲区对象(VBO)
    几何画板5.03
    VS(VisualStudio)中折叠代码、打开代码的快捷键
  • 原文地址:https://www.cnblogs.com/yingpu/p/9181013.html
Copyright © 2011-2022 走看看