從尾到頭打印鏈表
題目描述
輸入一個鏈表,按鏈表從尾到頭的順序返回一個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), 而不是直接採用下標索引。