輸入一個鏈表,按鏈表從尾到頭的順序回傳一個ArrayList,
思路一:使用堆疊先進后出的特點
/**
* 使用堆疊
* @param listNode
* @return
*/
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
if (listNode == null) return list;
if (listNode.next == null) {
list.add(listNode.val);
return list;
}
//先將鏈表放入堆疊中,在逐個彈堆疊即可
Stack<Integer> stack = new Stack<>();
while (true) {
if(listNode == null){
break;
}
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
思路二:利用遞回
/**
* 使用遞回
* @param listNode
* @return
*/
static ArrayList<Integer> listRecursion = new ArrayList<>();
public static ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
if(listNode !=null){
printListFromTailToHead2(listNode.next);
listRecursion.add(listNode.val);
}
return listRecursion;
}
節點類
public class InversionOfLinkedList {
/**
節點類
*/
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/248990.html
標籤:其他
上一篇:貪吃蛇—C語言控制臺簡單實作
下一篇:C++描述 1113. 紅與黑
