Title Description
Enter a linked list and return an ArrayList in the end-to-end order of the linked list values.
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { } }
Analysis
Analysis of ideas 1: from the end to the end of the printing list is not the use of the principle of first in and out, that is, we often say the stack.
Idea 2: From the return value type of the function, we can see that we need to return an ArrayList type, so we can declare an ArrayList directly from the linked list.
Traverse the data and store it in ArrayList.
Analysis Idea 3: From the end to the end of the output we can often consider recursion, we can gradually reduce the scale of the list, each time only take out one data. Save it in ArrayList.
Method 1:
Define stack structure
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { //Define Stack Stack<Integer> stack=new Stack<>(); //Traverse the list and merge it into the stack Stack while(listNode!=null){ stack.push(listNode.val); listNode = listNode.next; } //Define ArrayList because the return value is ArrayList ArrayList<Integer> list = new ArrayList<>(); //Stack out while(!stack.isEmpty()){ list.add(stack.pop()); } return list; }
Method two:
Order into ArrayList, reverse sort
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList<>(); //Method 1 //The add method allows us to insert data from end to end at index 0 before inserting it into a specific location. while(listNode!=null){ list.add(0,listNode.val); listNode = listNode.next; } //Method two //Save it in ArrayList and flip it with reverse // while(listNode!=null){ // list.add(listNode.val); // listNode = listNode.next; // } // Collections.reverse(list); return list; }
Method three:
recursion
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList<>(); if(listNode.next!=null){ list = printListFromTailToHead(listNode.next); } list.add(listNode.val); return list; }