一、题目描述
输入一个链表,从尾到头打印链表每个节点的值。
二、题解
方法一:
可以遍历这个链表,遍历过程中用一个ArrayList保存里面的值,然后再从尾到头遍历这个ArrayList,存储在新的ArrayList里面返回。
//使用另外一个ArrayList存储链表的方法
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode head=listNode;
while(head!=null) {
list.add(head.val);
head=head.next;
}
ArrayList<Integer> result=new ArrayList<Integer>();
for(int i=list.size()-1;i>=0;i--) {
result.add(list.get(i));
}
return result;
}
方法二:
“后进先出”,这时候就可以联想到栈这个数据结构。
Stack类是Vector类的子类.Vector类与ArrayList类的区别是,Vector是线程安全的,即在多线程的情况下,允许多个线程同时修改vector,但ArrayList是线程不安全的,需要在代码里保证其同步性,即一次只能有一个线程访问ArrayList.所以Vector的性能是比ArrayList要低的。
public static ArrayList<Integer> printListFromTailToHeadWithStack(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode head=listNode;
while(head!=null) {
stack.push(head.val);
head=head.next;
}
while(!stack.isEmpty()) {
Integer item=stack.pop();
list.add(item);
}
return list;
}
方法三:
由栈又很容易联想到递归。
链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
来源:牛客网
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}