第四题 从尾到头打印链表
输入一个链表,按链表值从尾到头的顺序返回一个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<Integer> re = new ArrayList<>();
ListNode res = helper(listNode);
if (listNode == null)
return re;
while (res != null) {
re.add(res.val);
res = res.next;
}
return re;
}
public ListNode helper(ListNode listNode) {
if (listNode == null || listNode.next == null)
return listNode;
ListNode newHead = helper(listNode.next);
listNode.next.next = listNode;
listNode.next = null;
return newHead;
}
}
解法二 用栈
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<>();
if(listNode == null) return res;
Stack<Integer> stack = new Stack<>();
while(listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
}
解法三 迭代
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode dummy = new ListNode(0);
while(listNode != null) {
ListNode next = listNode.next;
listNode.next = dummy.next;
dummy.next = listNode;
listNode = next;
}
ArrayList<Integer> res = new ArrayList<>();
dummy = dummy.next;
while(dummy != null) {
res.add(dummy.val);
dummy = dummy.next;
}
return res;
}
}