輸入一個連結串列,從尾到頭列印連結串列每個節點的值。
阿新 • • 發佈:2019-01-10
/** * 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> list=new ArrayList<>(); //如果連結串列為空,直接返回list if(listNode==null){ return list; } ListNode node=listNode; ListNode temp; //建立新的連結串列 ListNode node2=new ListNode(0); while(node!=null){ //頭插法 temp=new ListNode(node.val); temp.next=node2.next; node2.next=temp; node=node.next; } //遍歷連結串列 node2=node2.next; while(node2!=null){ list.add(node2.val); node2=node2.next; } return list; } }