从尾到头打印链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
方法1
采用stack实现逆序~
import java.util.Stack;
/**
* 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) {
//if(listNode == null) return null; // 返回的是列表,不是空!!!!
ArrayList<Integer> res = new ArrayList();
ListNode p = listNode;
Stack<Integer> stack = new Stack();
while(p != null){
stack.push(p.val);
p = p.next;
}
while(!stack.empty()){
res.add(stack.pop());
}
return res;
}
}
方法二
一个辅助ArrayLis,用于记录顺序的翻转结果
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//if(listNode == null) return null; // 返回的是列表,不是空!!!!
ArrayList<Integer> res = new ArrayList();
//ListNode p = listNode;
//Stack<Integer> stack = new Stack();
while(listNode != null){
res.add(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> ans = new ArrayList();
for(int i = res.size()-1; i >= 0; i--){
ans.add(res.get(i));
}
return ans;
}
}
notes
ArrayList用法:
ArrayList不是array,不能,length, 要用size(), 获取某个位置的元素值用get(i), 而不是直接采用下标索引。