剑指offer 3 从尾到头打印链表

来源:互联网 发布:网站防攻击软件 编辑:程序博客网 时间:2024/06/10 00:24

题目描述

输入一个链表,从尾到头打印链表每个节点的值。 
输入描述:
输入为链表的表头


输出描述:
输出为需要打印的“新链表”的表头
思路:
用一个递归方法遍历listnode,在递归结束时,将元素添加到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>temp=new ArrayList<Integer>();    public void find_path(ListNode listNode){        if(listNode==null)return ;        if(listNode.next!=null){            find_path(listNode.next);        }        Integer integer=new Integer(listNode.val);        temp.add(integer);            }    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {                find_path(listNode);    return temp;    }}


0 0
原创粉丝点击