- 輸入一個鏈表,按鏈表值從尾到頭的順序返回一個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) {
}
}
複製代碼
- 思路:看到從尾到頭想到棧,遍歷鏈表,壓入棧,遍歷棧,寫入ArrayList
- 代碼:
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (listNode == null) {
return list;
}
Stack<ListNode> stack = new Stack<ListNode>();
while (listNode != null) {
stack.push(listNode);
listNode = listNode.next;
}
while (!stack.empty()&&stack.peek()!=null){
list.add(stack.pop().val);
}
return list;
}
}
複製代碼