题目描述
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
解法一:递归实现(效率低)
import java.util.ArrayList; class ListNode{ int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { static ArrayList<Integer> arrayList = new ArrayList<Integer>(); public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if (listNode != null) { printListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } public static void main(String[] args) { ListNode a = new ListNode(1); ListNode b = new ListNode(2); ListNode c = new ListNode(3); a.next = b; b.next = c; System.out.println(printListFromTailToHead(a)); } }
解法
二:借助栈实现复杂度为O(n)
class ListNode{ int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { public static ArrayList<Integer> printListFromTailToHead(ListNode1 listNode) { Stack<Integer> stack = new Stack<Integer>(); ArrayList<Integer> arry = new ArrayList<Integer>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.empty()) { arry.add(stack.pop()); } return arry; } public static void main(String[] args) { ListNode1 a = new ListNode1(1); ListNode1 b = new ListNode1(2); ListNode1 c = new ListNode1(3); a.next = b; b.next = c; System.out.println(printListFromTailToHead(a)); } }