問題描述
力扣鏈接
輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
解題方法
典型後進先出,使用“棧”結構。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode cur = head;
while(cur != null){
stack.push(Integer.valueOf(cur.val));
cur = cur.next;
}
int size = stack.size();
int[] outarr = new int[size];
for(int i=0;i<size;i++){
outarr[i] = stack.pop().intValue();
}
return outarr;
}
}
查詢問題
棧的使用
使用方式
還有一個size()函數
JAVA中不建議使用stack
Integer與int之間的轉換
數組的定義方式
遞歸實現
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
存在問題:當鏈表很長的時候,會導致函數調用的層級很深,從而可能導致函數調用棧溢出。