题目描述
从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路: 核心算法
while(listNode!=null) { //倒置链表 头节点变成pre
next = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = next;
}
java实现
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode pre=null;
ListNode next=null;
while(listNode!=null){ //倒置链表 头节点变成pre
next=listNode.next;
listNode.next=pre;
pre=listNode;
listNode=next;
}
while(pre!=null){
list.add(pre.val);
pre=pre.next;
}
return list;
}
}