zoukankan      html  css  js  c++  java
  • 剑指offer三从头到尾打印链表

    一、题目:

      输入一个链表,从尾到头打印链表每个节点的值。

    二、解题方法:

      方法一:采用递归的方式实现

           方法二:借助堆栈的“后进先出”实现

    import java.util.ArrayList;
    import java.util.Stack;
    
    /**
     * 输入一个链表,从尾到头打印链表每个节点的值
     */
    class Test13 {
        public static void main(String[] args) {
            //创建单链表
            ListNode node1 = new ListNode(1);
            ListNode node2 = new ListNode(2);
            ListNode node3 = new ListNode(3);
            node1.next = node2;
            node2.next = node3;
    
            //采用递归的方式实现
            PrintListTailtoHead p = new PrintListTailtoHead();
            ArrayList<Integer> list = p.printListFromTailToHead(node1);
            System.out.println(list.toString());
    
            System.out.println("-------------");
    
            //借助堆栈的“后进先出”实现(容易理解)
            PrintListTailtoHead2 p2 = new PrintListTailtoHead2();
            ArrayList<Integer> list2 = p2.printListFromTailToHead2(node1);
            System.out.println(list2.toString());
        }
    }
    
    
    //节点
    class ListNode {
        int value;
        ListNode next = null;
    
        ListNode() {}
    
        ListNode(int value) {
            this.value = value;
        }
    }
    
    //方法1:采用递归的方式实现
    class PrintListTailtoHead {
        public ArrayList<Integer> printListFromTailToHead(ListNode headNode) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            //递归
            if (headNode != null) {
                if (headNode.next != null) {
                    list =printListFromTailToHead(headNode.next);
                }
                list.add(headNode.value);
            }
            return list;
        }
    }
    
    //方法2:借助堆栈的“后进先出”实现
    class PrintListTailtoHead2{
        public ArrayList<Integer> printListFromTailToHead2(ListNode headNode) {
            //存入栈中
            Stack<Integer> stack=new Stack<Integer>();
            while (headNode!=null){
                stack.push(headNode.value);
                headNode=headNode.next; //重要,不要忘记
            }
    
            //从栈中取出存入集合中
           ArrayList<Integer> arrayList=new ArrayList<Integer>();
            while (!stack.empty()) {
                arrayList.add(stack.pop());
    
            }
    
            //返回结果
            return arrayList;
        }
    }
    View Code
  • 相关阅读:
    GridView与ArrayAdapter的结合
    翻翻git之---闪烁动画的TextView RevealTextView
    希捷硬盘扩容软件-----DiscWizard
    项目管理的酸甜苦辣
    【转】Bootloader之uBoot简介(转)
    【转】uboot移植(一)BootLoader基本概念
    【转】U-boot分析与移植(1)----bootloader分析
    【转】MIPS交叉编译环境的建立
    【转】RTSP实例解析
    【转】Eclipse快捷键 10个最有用的快捷键----不错
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/7609577.html
Copyright © 2011-2022 走看看