标签:new ret 尾到头 div port get stat next arraylist
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/** * 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<>(); if(listNode==null)return list; if(listNode.next==null){ list.add(listNode.val); return list; } while (listNode.next!=null){ list.add(listNode.val); listNode=listNode.next; } list.add(listNode.val); ArrayList<Integer> list1=new ArrayList<>(); for(int i=list.size()-1;i>=0;i--){ list1.add(list.get(i)); } return list1; } }
import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Solution { public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { Stack<Integer> stack = new Stack<>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } ArrayList<Integer> list = new ArrayList<>(); while (!stack.isEmpty()) { list.add(stack.pop()); } return list; } }
标签:new ret 尾到头 div port get stat next arraylist
原文地址:https://www.cnblogs.com/yihangZhou/p/10197839.html