输入一个链表,按链表从尾到头的顺序返回一个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<>();
ListNode pre = listNode;
while(pre != null){
list.add(0,pre.val);
pre = pre.next;
}
return list;
}
}
***********************************************************************************************************
②
/**
* 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> res = new ArrayList<>();
if(listNode == null){
return res;
}
ListNode pre = null;
ListNode currentNode = listNode;
while(currentNode != null){
ListNode next = currentNode.next;
currentNode.next = pre;
pre = currentNode;
currentNode = next;
}
while(pre != null){
res.add(pre.val);
pre = pre.next;
}
return res;
}
}