剑指 Offer 06. 从尾到头打印链表
题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
Input: head = [1,3,2]
Output: [2,3,1]
解题思路:
- 这道题比较简单,由于题目要求用数组返回,那么一般都可以想到创建一个链表长度一样大小的数组即可,链表长度则是通过遍历链表而获得。最后就通过倒着索引来给数组赋值即可。
- 第二种方法通过看题解,发现可以通过栈来存储链表元素。题目要求从尾到头打印链表,也就是将链表反转。而栈有着先进后出的特点,因此链表的尾节点元素会出现在栈顶,这时再将栈元素一一弹出到数组即可。但是这会消耗额外的空间(多了一个栈)
- 第三种跟栈类似,是通过递归的方法,将每个元素存入一个列表中,然后再将列表元素转到数组。
算法代码:
// 通过数组
class Solution {
public int[] reversePrint(ListNode head) {
int size = 0;
ListNode nextNode = head;
while(nextNode!=null){
size++;
nextNode = nextNode.next;
}
int[] res = new int[size];
for(int i = size-1; i>=0; i--){
res[i] = head.val;
head = head.next;
}
return res;
}
}
// 通过栈存储,参考官方代码
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}
// 通过递归,参考Krahets大神代码
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
如有错误,欢迎大家留言指出,大家一起进步