剑指offer_从尾到头打印链表

来源:互联网 发布:淘宝2016销售额是多少 编辑:程序博客网 时间:2024/06/17 04:33
/*问题:从尾至头打印链表思路:对于单链表,从头至尾遍历保存到ArrayList中,再从后向前打印,也可以使用栈来保存*/import java.util.ArrayList;class  PrintListFromTailToHead{//非递归,直接打印public static void printListFromTailToHead(ListNode listnode){if(listnode==null)return;ArrayList<Integer> al=new ArrayList<Integer>();ListNode temp=listnode;while(temp!=null){al.add(temp.val);temp=temp.next;}for (int i=al.size()-1; i>=0;i-- ){System.out.println(al.get(i));}}//剑指offer递归解法,保存到ArrayList public static  ArrayList<Integer> list=new ArrayList<Integer>(); public static  ArrayList<Integer> printListFromTailToHead2(ListNode listNode){        if(listNode!=null){printListFromTailToHead2(listNode.next);         list.add(listNode.val);}                return list;    }public static void main(String[] args) {ListNode node1=new ListNode(1);ListNode node2=new ListNode(2);ListNode node3=new ListNode(3);ListNode node4=new ListNode(4);node1.next=node2;node2.next=node3;node3.next=node4; ArrayList<Integer> output=printListFromTailToHead2(node1);for(int i:output){System.out.println(i);}}}class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}}