Java语言解题简单实现(从尾到头打印链表)
从尾到头打印链表
http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
JAVA实现
先保存到一个中间List中,然后倒序获取元素,存入新的List,返回结果。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode currentNode = listNode;
ArrayList<Integer> tempList = new ArrayList<Integer>();
while(currentNode != null){
tempList.add(currentNode.val);
currentNode = currentNode.next;
}
// 翻转
ArrayList<Integer> endList = new ArrayList<Integer>();
for(int i=tempList.size()-1; i>=0; i--){
endList.add(tempList.get(i));
}
return endList;
}
}