The print head from the end of the list
Title Description
Enter a list, the value returned by a ArrayList list sequentially from the tail to the head.
Problem-solving ideas
Solution 1: traversal order
The easiest way is to traverse the list sequentially, need the help of JavaScript
several methods of an array of built-in
Array.reverse()
Traversal order, into an array of values, the array is flipped
function printListFromTailToHead(head)
{
// write code here
var res = [];
while(head != null){
res.push(head.val);
head = head.next;
}
return res.reverse();
}
Array.unshift
unshift
A head insertion elements in the array, and push
the opposite
function printListFromTailToHead(head)
{
// write code here
var res = [];
while(head != null){
res.unshift(head.val);
head = head.next;
}
return res;
}
The inverted node pointer: Method 2
Solution 3: Recursive
- Every one will be on the array returned by the
push
operation, insert the current element - Termination point for the returned array [], the element is inserted from back to front
//.js
function printListFromTailToHead(head)
{
// write code here
var res = [];
if (head != null){
res = printListFromTailToHead(head.next);
res.push(head.val);
}
return res;
}
Note that Java is used ArrayList.add (), not push
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
if (listNode != null){
arrayList = printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}