题解 | #从尾到头打印链表#
从尾到头打印链表
http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
- 使用函数递归的做法,发现会出现stackOverFlow;
- 遍历链表节点,存到ArrayList,将ArrayList倒序存到新的ArrayList;
- 在2的基础上可以再优化,不需要创建一个新的ArrayList,直接用翻转链表的方式,左右倒转返回。
```
/**
- public class ListNode {
- int val;
- ListNode next = null;
- ListNode(int val) {
- this.val = val;
- }
- }
- /
import java.util.ArrayList;
public class Solution {
public ArrayList<integer> printListFromTailToHead(ListNode listNode) {
ArrayList<integer> printList = new ArrayList();
if (listNode == null) {
return printList;
}
ListNode header = listNode;
while(header != null) {
printList.add(header.val);
header = header.next;
}</integer></integer>
// ArrayList<integer> resultList = new ArrayList();
// for (int i = printList.size() - 1; i >= 0; i--) {
// resultList.add(printList.get(i));
// }
// return resultList;
int size = printList.size();
for (int i = 0; i < size / 2; i++) {
int left = printList.get(i);
int right = printList.get(size - i - 1);
printList.set(i, right);
printList.set(size - i - 1, left);
}
return printList;
}
}
```</integer>