/**
* 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> arraylist = new ArrayList<Integer>();
//为空返回
if(listNode == null) return arraylist;
ListNode p = listNode.next;
listNode.next = null;
ListNode q = listNode;
while(p != null) {
q = p;
p = p.next;
q.next = listNode;
listNode = q;
}
while(q != null) {
arraylist.add(q.val);
q = q.next;
}
return arraylist;
}
}
链表的就地逆置,然后从新的头结点开始将节点输入到ArrayList数组中,注意如果传入的节点内容为空,不能直接返回null

京公网安备 11010502036488号