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

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

  • 相关阅读:
    闰年测试
    EditBox的测试用例设计
    测试工程中的评审
    测试框架
    github
    第一次上机实验
    对软件测试的初步认识
    白盒测试
    Date : 日期对象
    C++ 格式化输出 及 输入 流
  • 原文地址:https://www.cnblogs.com/yingpu/p/9181013.html
Copyright © 2011-2022 走看看