0003 list print head from the tail
Title Description
Input a linked list, returns a value from the list according to the order of the tail to the head ArrayList
.
Topics address
- https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
Report problem-solving
With the stack output
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<Integer>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
With a collection of reversal
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
while(listNode != null){
list.add(listNode.val);
listNode = listNode.next;
}
Collections.reverse(list);
return list;
}
}
With a collection insert
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
Traverse the list of 0 to traverse each list element into a set of
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
while(listNode != null){
list.add(0, listNode.val);
listNode = listNode.next;
}
return list;
}
}
Recursive thinking
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public class Solution {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode != null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}