Java implementation from start to finish printing the list [to prove safety offer]

topic

Enter a list, by returning a list sequentially from the tail to the head of ArrayList.
The first thought might be to reverse a linked list, but according to the meaning of the questions, it should not change the structure of the list.

1 is achieved by thinking stack

1.1 Description

After the list of nodes on the more, the more prints, last-out in line with the idea of ​​using the ArrayList class add methods to specify the index, will be placed on the top of the list to the current node

1.2code

 1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
 2         //1.通过栈的思想实现
 3         ArrayList<Integer> list=new ArrayList<Integer>();
 4         if(listNode!=null){
 5            while(listNode!=null){
 6                list.add(0,listNode.val);
 7                listNode=listNode.next;
 8            }
 9         }
10         return list;
11     }

2 is achieved by recursive

2.1 Description

Recursive nature is a stack structure, when accessing to a node, to not output, the first output node to the next node, and then output itself

2.2code

 1 public class Solution {
 2     ArrayList<Integer> list=new ArrayList<Integer>();
 3     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
 4         if(listNode!=null){
 5             printListFromTailToHead(listNode.next);
 6             list.add(listNode.val);
 7         }
 8         return list;
 9     }
10 }

 

Guess you like

Origin www.cnblogs.com/ERFishing/p/11831522.html