剑指offer题解 从尾到头打印链表

来源:互联网 发布:黑客网络攻击技术 编辑:程序博客网 时间:2024/06/11 19:37

题目描述

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

输入为链表的表头

输出描述:

输出为需要打印的“新链表”的表头

采用头插法,每次都往ArrayList第0个位置添加数据。这样添加完后,链表的最后一个数据就排在最前面了。依次逆序排放。

/***    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) {        if(null==listNode) return new ArrayList<Integer>();        ArrayList<Integer> mStack=new ArrayList<Integer>();        ListNode head=listNode;        while(head!=null){            mStack.add(0,head.val);            head=head.next;        }        return mStack;    }}
0 0
原创粉丝点击