import java.util.ArrayList;
public class ReverseListNode {
static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> intList = new ArrayList<>();
ArrayList<Integer> intList2 = new ArrayList<>();
ListNode node = listNode;
while(node != null){
intList.add(node.val);
node = node.next;
}
int size = intList.size();
for(int i=size-1; i>=0; i--){
intList2.add(intList.get(i));
}
return intList2;
}
public static ListNode printListFromTailToHead2(ListNode listNode) {
ListNode newNode = null;
ArrayList<ListNode> nodeList = new ArrayList<>();
ListNode next = listNode.next;
listNode.next = null;
nodeList.add(listNode);
while(next!=null){
nodeList.add(next);
next=next.next;
}
int size = nodeList.size();
int index = size -1;
while(index>=1) {
nodeList.get(index).next = nodeList.get(index-1);
index --;
}
newNode = nodeList.get(size-1);
return newNode;
}
public static ListNode printListFromTailToHead3(ListNode listNode) {
ListNode newNode = null;
ArrayList<ListNode> nodeList = new ArrayList<>();
ListNode next = listNode.next;
listNode.next = null;
nodeList.add(listNode);
int index = 1;
ListNode current;
while(next!=null){
nodeList.add(next);
next=next.next;
nodeList.get(index).next=nodeList.get(index-1);
index++;
}
int size = nodeList.size();
newNode = nodeList.get(size-1);
return newNode;
}
public static void main(String[] args) {
ListNode node = new ListNode(20);
ListNode node1 = new ListNode(30);
ListNode node2 = new ListNode(40);
ListNode node3 = new ListNode(50);
node.next=node1; node1.next=node2; node2.next=node3;
System.out.println(node);
ArrayList<Integer> list = printListFromTailToHead(node);
System.out.println(list);
ListNode listNode = printListFromTailToHead3(node);
System.out.println(listNode.next);
}
}