https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
思路:遍历链表将每个节点的值存入数组中,然后将数组反转返回。
学习一下如何定义链表!
public class print_linked_list_from_end_to_end {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
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 arrayList = printListFromTailToHead(node1);
System.out.println(arrayList);
}
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList arrayList = new ArrayList();
while (listNode != null) {
arrayList.add(listNode.val);
listNode = listNode.next;
}
Collections.reverse(arrayList);
return arrayList;
}
}