剑指 Offer 06. 从尾到头打印链表
难度:简单
题目描述
解题思路
1、用栈辅助
/*
* 剑指 Offer 06. 从尾到头打印链表
* 2020/6/30
*/
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode p = head;
while(p != null) {
stack.push(p.val);
p = p.next;
}
int[] re = new int[stack.size()];
for (int i = 0; i < re.length; i++) {
re[i] = stack.pop();
}
return re;
}
2、递归
public int[] reversePrint(ListNode head) {
List<Integer> list = new LinkedList<>();
printHelper(head,list);
int[] re = new int[list.size()];
for (int i = 0; i < re.length; i++) {
re[i] = list.get(i);
}
return re;
}
public void printHelper(ListNode head,List<Integer> list) {
if(head == null)
return;
printHelper(head.next, list); //这里一定要先遍历next,再添加
list.add(head.val);
}
3、两次遍历 双百
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode p = head;
while(p != null) {
count++;
p = p.next;
}
int[] re = new int[count];
p = head;
while(p != null) {
re[--count] = p.val;
p = p.next;
}
return re;
}