//思路一:
//先反转链表,在从头到尾打印
//从尾到头打印链表
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<>();
//逆置该链表
ListNode head = reverse(listNode);
while(head!=null){
res.add(head.val);
head = head.next;
}
return res;
}
private ListNode reverse(ListNode listNode){
ListNode pre = null;
ListNode cur = listNode;
while(cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//思路二:
//递归思路
//要逆序打印链表 1->2->3(3,2,1),可以先逆序打印链表 2->3(3,2),最后再打印第一个节点 1。
//链表 2->3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数。
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<>();
if (listNode == null){
return res;
}
if(listNode.next==null){
res.add(listNode.val);
return res;
}
ArrayList<Integer> next = printListFromTailToHead(listNode.next);
res.addAll(next);
res.add(listNode.val);
return res;
}
https://www.mianshi.online,https://www.i9code.cn
本文由博客一文多发平台 OpenWrite 发布!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。