Offer surface prove safety questions 6 (java version): the print head from the end of the list

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91383106

welcom to my blog

6 is inscribed: list print head from the tail

Title Description

Enter a list, the value returned from the sequence list by the end head of an ArrayList

Thinking

  • Last-out: stack structure, LinkedList stack data structure can be achieved
  • Little attention to the generic issue

the complexity

Time complexity: O (n)
space complexity: O (n)

import java.util.ArrayList;
import java.util.LinkedList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        // 健壮性判断. 加上下面这个健壮性判断就错了!
        //if(listNode == null)
            //return null;
        // 开始处理
        LinkedList<Integer> ll = new LinkedList();
        while(listNode != null){
            ll.addFirst(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> al = new ArrayList();
        while(!ll.isEmpty()){
            al.add(ll.remove());
        }
        return al;
    }
}

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91383106