链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035?answerType=1&f=discussion
来源:牛客网
[编程题]从尾到头打印链表
- 热度指数:1468661 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
- 算法知识视频讲解
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1
输入
{67,0,24,58}
输出
[58,24,0,67]
分析:
这里面其实不是什么难点,就是一个链表逆序的问题。
然后我主要是我为了增加自己的算法熟练度的,所以更多的时候是使用自己不熟练的方案。所以会有优化版本,如果我没有写出来,各位大佬可以评论区教一下!!!
/**
*方法一:递归实现,定义一个递归函数,完成递归即可。
* 注意判断为空链表的情况即可
*/
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if (listNode != null){
backout(result, listNode);
}
return result;
}
private void backout(ArrayList<Integer> result, ListNode listNode) {
if (listNode.next != null) {
backout(result, listNode.next);
result.add(listNode.val);
} else {
result.add(listNode.val);
return;
}
}
/**
* 方法二:在外部定义一个返回类型的变量,然后直接利用命题函数实现递归。
* 这个方法在我工作以后不是很喜欢用,因为这个成员变量不利于数据的安全性
*/
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
printListFromTailToHead(listNode.next);
list.add(listNode.val);
}
return list;
}
/**
*方法三,利用ArrayList中插入方法的特性,指定对应位置的插入,同时将原数据后移。
* 这个方案一开始我也没有想到,因为这个对jdk的api用习惯以后有一定的惯性思维。
* 后面我贴出add方法的api说明:
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*/
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
ListNode tmp = listNode;
while(tmp!=null){
list.add(0,tmp.val);
tmp = tmp.next;
}
return list;
}