题目描述:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
package Algorithm.Offer.T3;
import Algorithm.common.ListNode;
import Algorithm.common.ListNodeUtil;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
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;
}
public static ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
if (listNode == null)
return list;
list.add(0, listNode.val);
ListNode temp = listNode.next;
while (temp != null) {
list.add(0, temp.val);
temp = temp.next;
}
return list;
}
public static void main(String[] args) {
long start = System.nanoTime();
ListNodeUtil listNodeUtil = new ListNodeUtil();
int[] arr = {1, 2, 3, 4, 5};
ListNode listNode = listNodeUtil.buildListNode(arr);
System.out.println(printListFromTailToHead(listNode));
long end = System.nanoTime();
System.out.println("运行时间:" + (end - start) + "ns");
}
}
package Algorithm.common;
public class ListNodeUtil {
public static ListNode buildListNode(int[] input) {
if (input.length == 0)
return null;
ListNode head = new ListNode(input[0]);
ListNode currentNode = head;
for (int i = 1; i < input.length; i++) {
currentNode.next = new ListNode(input[i]);
currentNode = currentNode.next;
}
return head;
}
}
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}