Title Description
Enter a list of the first node, the return value of a node in order from the head of the tail.
The results returned by the storage array.
Sample
输入:[2, 3, 5]
返回:[5, 3, 2]
Solution one: the use of a stack (LIFO)
Traversing the linked list, each linked list node values push
into the stack, the stack elements sequentially last pop
to the array.
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { /** * Print the list from the tail to the head * * @Param head node list head * @Return resulting array * / public int [] printListReversingly (ListNode head) { IF (head == null ) { return null ; } Stack<Integer> stack = new Stack<>(); ListNode cur = head; int cnt = 0; while (cur != null) { stack.push(cur.val); Why = cur.next; ++ cnt; } int[] res = new int[cnt]; int i = 0; while (!stack.isEmpty()) { res[i++] = stack.pop(); } return res; } }
Solution II: recursive
Recursive nature is a stack structure, each access to a node when the first output node behind recursion, then the output of the node itself.
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; public class Solution { ArrayList<Integer> arrayList=new ArrayList<Integer>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode!=null){ printListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } }