package lianbiao;
import java.util.ArrayList;
import java.util.Collections;
/**
* 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
*/
public class Solution {
// 测试主程序
public static void main(String args[]) {
// 创建链表
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
// 调用逆转链表函数
ArrayList<Integer> now = printListFromTailToHead(node1);
System.out.println(now);
}
// 链表节点的结构
static public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
// 调转函数
static public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> temp = new ArrayList<Integer>();
if (listNode != null) {
temp.add(listNode.val);
ListNode nextnode = listNode.next;
while (nextnode != null) {
temp.add(nextnode.val);
nextnode = nextnode.next;
}
Collections.reverse(temp);
}
return temp;
}
}