题目描述:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:
1.头插法,改变指针指向。
2.递归的思想。
public class ListNode { //结点定义
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
//1. 头插法,操作指针
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> A=new ArrayList<Integer>();
if(listNode==null) return A;
ListNode head=listNode,p=head.next,t=p;
head.next=null;
while(t!=null) {
t=t.next;
p.next=head;
head=p;
p=t;
}
//存入集合
while(head!=null) {
A.add(head.val);
head=head.next;
}
return A;
}
//2.递归
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
if(listNode!=null){
printListFromTailToHead2(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}