• 单链表翻转


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

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

  • 相关阅读:
    运动世界校园破解2.0
    Docker进阶操作
    一键开启https
    Docker的第一次实践总结
    手机通话黑屏
    mysql安装、操作、配置、远程
    excel添加列数据导入后,列数据不显示的问题
    常见邮箱的各类协议服务器地址
    POP3/SMTP/IMAP等邮箱协议的基本概念
    You credentials did not work (The logon attempt failed)
  • 原文地址:https://www.cnblogs.com/yingpu/p/9181013.html
Copyright © 2020-2023  润新知