剑指offfer 从尾到头打印链表
1.for循环
class Solution {
public int[] reversePrint(ListNode head) {
ListNode temp = head;
int n = 0;
while(temp!=null){
temp = temp.next;
n++;
}
int[] a = new int[n];
//将链表中的值倒着存入数组
for(int i = n-1;i>=0;i--){
a[i] = head.val;
head = head.next;
}
return a;
}
}
2.递归
class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
//调用递归函数,将链表中的元素反向追加到list中
digui(head);
int[] a = new int[list.size()];
for(int i = 0;i<list.size();i++){
a[i] = list.get(i);
}
return a;
}
void digui(ListNode head){
if(head==null) return;
digui(head.next);
//回溯时将每个节点的值添加到list中
list.add(head.val);
}
}
本文来自博客园,作者:蹇爱黄,转载请注明原文链接:https://www.cnblogs.com/jianjiana/p/15860311.html