**输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。**
//递归 方法
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(listNode!=null){
list=printListFromTailToHead( listNode.next);
list.add(listNode.val);
}
return list;
}
}
import java.util.Stack;// 使用栈 先进后出
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
ListNode node=listNode;
while(node!=null){
stack.push(node.val);
node = node.next;
}
while(!stack.empty()){
list.add(stack.pop());
}
return list;
}
}
//链表逆序
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode==null){
return new ArrayList<Integer>();
}
ArrayList<Integer> list = new ArrayList<Integer>();
ListNode head = listNode;
ListNode cur = listNode.next;
// head.next=null;
while(cur!=null){
ListNode temp=cur.next;
cur.next=head;
head=cur;
cur=temp;
}
listNode.next = null;
while(head!=null){
list.add(head.val);
head=head.next;
}
return list;
}
}
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/