剑指Offer面试题5 Java解法

    xiaoxiao2026-08-28  14

    题目:输入一个链表,从尾到头打印链表每个节点的值。 
    输入描述:
    输入为链表的表头
    输出描述:
    输出为需要打印的“新链表”的表头 该题的解题思路是递归或者是栈: 递归解法:public static void printListReverse1(ListNode headNode){ if (headNode != null){ if(headNode.next != null){ printListReverse1(headNode.next); } } System.out.println(headNode.val); }栈的解法: public static void printListReverse(ListNode headNode){ Stack<ListNode> stack = new Stack<ListNode>(); while (headNode != null){ stack.push(headNode); headNode = headNode.next; } while (!stack.empty()){ System.out.println(stack.pop().val); } }还有这种递归方法挺难理解的,现在我还是不咋理解哈哈,debug一下看到了程序走的步骤,反正让我写我是写不出来,有兴趣的可以思考下: public class Solution { ArrayList<Integer> arrayList=new ArrayList<Integer>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode!=null){ this.printListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } }
    转载请注明原文地址: https://ju.6miu.com/read-1311661.html
    最新回复(0)