首页 > 其他 > 详细

从尾到头打印链表

时间:2020-09-12 22:45:30      阅读:59      评论:0      收藏:0      [点我收藏+]

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


解法一:最简单的想法,先排序,再逆序

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> integerList = new ArrayList<>();
 
        while (listNode != null) {
            integerList.add(listNode.val);
            listNode = listNode.next;
        }
        // 不想调用库函数也行,自己写一个叭
        Collections.reverse(integerList);
        return integerList;
    }
}

解法二:借助栈先进后出的原理,辅助实现逆序

import java.util.Stack;
import java.util.ArrayList;
public class Solution {
    private Stack<Integer> stack = new Stack<>();
    private ArrayList<Integer> list = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        while(listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(stack.size() > 0) {
            list.add(stack.pop());
        }
        return list;
    }
}

解法三:使用递归思想,递归其实也类似于栈的调用

public class Solution {
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode != null){
            this.printListFromTailToHead(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}

解法四:使用头插法实现

对于 ArrayList 来说,数组元素移动的开销太大,不建议使用,但思路是不错的

public class Solution {
    private ArrayList<Integer> list = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        while(listNode != null) {
            list.add(0, listNode.val);
            listNode = listNode.next;
        }
        return list;
    }
}

小结:涉及到逆序问题,可以往以下方面考虑

  • 借助栈先进后出的特点
  • 递归也可以实现栈的作用
  • 头插法是把新结点插入首部,其余结点往后退,也是一个值得考虑的方案

从尾到头打印链表

原文:https://www.cnblogs.com/Yee-Q/p/13658458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!