算法系列——从尾到头打印链表(剑指offer)

来源:互联网 发布:最好的中国象棋软件 编辑:程序博客网 时间:2024/06/10 18:07

题目描述

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

解题思路

可以利用栈先进后出的特性,将结点依次进栈。最后再依次出栈即可。

递归法

同样可以利用递归的方法。

程序实现

 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        ArrayList<Integer> res=new ArrayList<Integer>();       Stack<Integer> s=new Stack<Integer>();        while(listNode!=null){            s.push(listNode.val);            listNode=listNode.next;        }        while(s.size()>0){             res.add(s.pop());        }        return res;    }

递归

public class Solution {    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        ArrayList<Integer> res=new ArrayList<Integer>();        print(listNode,res);        return res;    }    private void print(ListNode listNode,ArrayList<Integer> res){        if(listNode==null)            return;        if(listNode.next!=null)           print(listNode.next,res);        res.add(listNode.val);    }}
原创粉丝点击