题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
代码
头插法
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode curr = listNode;
ArrayList<Integer> ret = new ArrayList<>();
while(curr != null)
{
ret.add(0, curr.val);
curr = curr.next;
}
return ret;
}
}
栈
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
Stack<Integer> stk = new Stack<>();
ListNode curr = listNode;
while(curr != null)
{
stk.push(curr.val);
curr = curr.next;
}
while(!stk.isEmpty())
{
ret.add(stk.pop());
}
return ret;
}
}