劍指 Offer - 3:從尾到頭列印連結串列
阿新 • • 發佈:2018-11-26
題目描述
輸入一個連結串列,按連結串列值從尾到頭的順序返回一個ArrayList
題目連結:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
解題思路
藉助棧
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>( );
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> result = new ArrayList<>();
while (!stack.isEmpty()) {
result.add(stack.pop());
}
return result;
}
}
使用遞迴的方式
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if (listNode == null) return result;
result.addAll(printListFromTailToHead(listNode.next));
result. add(listNode.val);
return result;
}
}
藉助連結串列原地反轉的思想
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if (listNode == null) return result;
if (listNode.next == null) {
result.add(listNode.val);
return result;
}
ListNode pre = null;
ListNode next = null;
while (listNode != null) {
next = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = next;
}
while (pre != null) {
result.add(pre.val);
pre = pre.next;
}
return result;
}
}