Wins the offer (3) of the print head from the end of the list

Title: Enter a list, by returning a list sequentially from the tail to the head of ArrayList.

Method One: non-recursive

    1 ideas: first with each node linked list traversal while loop, and the value for each node stored in an ArrayList, ArrayList after reverse traversal, the value stored into another ArrayList, and then returns

    code show as below:

 1 import java.util.ArrayList;
 2 
 3 class ListNode
 4 {
 5 
 6     int val;
 7     ListNode next;
 8     ListNode(int x)
 9     {
10         val = x;
11     }
12 }
13 
14 public class Solution {
15     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
16         ArrayList<Integer> list=new ArrayList<Integer>();
17         ArrayList<Integer> list2=new ArrayList<Integer>();
18          
19         while (listNode!=null)
20         {
21             list.add(listNode.val);
22             listNode=listNode.next;
23         } 
24         for (int i = list.size()-1; i >= 0; i--)
25         {
26             list2.add(list.get(i));
27         }
28          
29         return list2;
30  
31     }
32 }

    2 ideas: the idea is to traverse, but using a direct method of ArrayList list.add(0,listNode.val), inserted from scratch each time, a reverse list

    code show as below:

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
 4         ArrayList<Integer> list=new ArrayList<Integer>();
 5          
 6          
 7         while (listNode!=null)
 8         {
 9             list.add(0,listNode.val);
10             listNode=listNode.next;
11         } 
12          
13         return list;
14  
15     }
16 }

Method Two: Recursive

    Ideas: Every recursive call method using sub node in the method before the add operation ArrayList, so that when the end of the recursive call will first run the add method of the last node, add in turn, generates a reverse return ArrayList

    code show as below:

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

 

Guess you like

Origin www.cnblogs.com/quxiangjia/p/12520577.html