题目描述:
从尾到头打印链表。
方法一:使用辅助栈
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode == null)
return new ArrayList<Integer>();
//使用辅助栈
Stack<Integer> stack = new Stack<>();
ListNode p = listNode;
while(p != null) {
stack.push(p.val);
p = p.next;
}
ArrayList<Integer> result = new ArrayList<>();
while(!stack.isEmpty()) {
result.add(stack.pop());
}
return result;
}
}
方法二:采用递归
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode == null) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<>();
//递归
corePrint(listNode, result);
return result;
}
//递归函数
public void corePrint(ListNode node, ArrayList<Integer> result) {
if(node == null) {
return;
}
corePrint(node.next, result);
result.add(node.val);
}
}
网友评论