• 剑指offer:面试题5、从尾到头打印链表


    题目描述

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

    代码示例

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Stack;
    
    public class Offer5 {
        public static void main(String[] agrs) {
            //构建链表
            ListNode head = new ListNode(1);
            head.next = new ListNode(2);
            head.next.next = new ListNode(3);
            Offer5 testObj = new Offer5();
            //打印列表
            testObj.printList(head);
            //测试法1
    //        List<Integer> res = testObj.printListFromTailToHead(head);
            //测试法2
    //        List<Integer> res = testObj.printListFromTailToHead2(head);
            //测试法3
            List<Integer> res = testObj.printListFromTailToHead3(head);
            System.out.println(res);
        }
    
        //法1:最容易想到的使用栈
        public List<Integer> printListFromTailToHead(ListNode listNode) {
            Stack<Integer> stack = new Stack<>();
            while (listNode != null) {
                stack.add(listNode.val);
                listNode = listNode.next;
            }
            List<Integer> res = new ArrayList<>();
            while (!stack.isEmpty()) {
                res.add(stack.pop());
            }
            return res;
        }
    
        //法2:头插法逆序链表
        public List<Integer> printListFromTailToHead2(ListNode listNode) {
            ListNode head = new ListNode(-1);
            while (listNode != null) {
                ListNode next = listNode.next;
                listNode.next = head.next;
                head.next = listNode;
                listNode = next;
            }
            List<Integer> res = new ArrayList<>();
            head = head.next;
            while (head != null) {
                res.add(head.val);
                head = head.next;
            }
            return res;
        }
    
        //法3:使用递归
        public List<Integer> printListFromTailToHead3(ListNode listNode) {
            List<Integer> res = new ArrayList<>();
            if (listNode != null) {
                res.addAll(printListFromTailToHead3(listNode.next));
                res.add(listNode.val);
            }
            return res;
        }
    
        private void printList(ListNode head) {
            if (head == null) {
                return;
            }
            while (head != null) {
                System.out.println(head.val);
                head = head.next;
            }
        }
    
        static class ListNode {
            int val;
            ListNode next;
            ListNode(int val) {
                this.val = val;
            }
        }
    }
    
    
  • 相关阅读:
    poj2739
    poj1469
    poj2010
    poj1179
    poj1778
    使用数组实现ArrayList的效果
    zgb老师关于java集合的总结
    jah老师中关于集合的总结
    继承一个类或者是实现一个接口注意点
    5、Iterator迭代器的使用
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13138681.html
Copyright © 2020-2023  润新知