從尾到頭反過來打印出每一個結點的值java
頭插法可將鏈表反轉編程
/** * 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) { ArrayList<Integer> ret=new ArrayList<>(); ListNode dummy=new ListNode(-1); ListNode cur=listNode; while(cur!=null){ ListNode next=cur.next; cur.next=dummy.next; dummy.next=cur; cur=next; } cur=dummy.next; while(cur!=null){ ret.add(cur.val); cur=cur.next; } return ret; } }