The print head from the end of the list

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 JavaScriptseveral 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

unshiftA head insertion elements in the array, and pushthe 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 pushoperation, 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;
    }
}
Published 241 original articles · won praise 14 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_29150765/article/details/102504664