Enter a list to print the values of each node of the list from the end of the head.
I started with the idea of traversing the list, using a ArrayList to hold the value inside, and then traversing the ArrayList from the tail to the back of the new ArrayList.
Use another method of ArrayList to store the list public static arraylist<integer> Printlistfromtailtohead (ListNode listnode) { Arraylist<integer> list=new arraylist<integer> (); ListNode Head=listnode;while (head!=null) {list.add (head.val); head=head.next;} Arraylist<integer> result=new arraylist<integer> (); for (int i=list.size () -1;i>=0;i--) {Result.add ( List.get (i));} return result;}
Later saw the sword refers to the offer, found in fact, if it is from the end of the printing chain list, because this is a one-way list, and does not store the value of the previous list, so we can only print the list from start to finish, so-called "LIFO", this time you can associate to the data structure of the stack.
The Stack class is a subclass of the vector class. The difference between a vector class and a ArrayList class is that vectors are thread-safe, which allows multiple threads to modify vectors at the same time in multithreaded situations, but ArrayList is thread insecure. It is necessary to ensure its synchronicity in the code that only one thread at a time accesses ArrayList. So the performance of vectors is lower than that of ArrayList.
public static arraylist<integer> Printlistfromtailtoheadwithstack (ListNode listnode) {stack<integer> stack = new stack<integer> (); Arraylist<integer> list=new arraylist<integer> (); ListNode Head=listnode;while (head!=null) {Stack.push (head.val); head=head.next;} while (!stack.isempty ()) {Integer item=stack.pop (); List.add (item);} return list;}
It is easy to associate recursion with stacks.
static arraylist<integer> result;public static void print (ListNode listnode) {if (listnode!=null) {print ( Listnode.next); Result.add (listnode.val);} }//using recursive public static arraylist<integer> printlistfromtailtoheadwithrecursion (ListNode listnode) {result=new Arraylist<integer> ();p rint (listnode); return result;}
offer-The chain list from the tail to the head