题目来源
题目链接如下:点击跳转
题目介绍
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
限制
0 <= 链表长度 <= 10000
解题思路
-
思路一
– 用数组返回,数组索引可以倒序存储,从而实现从尾到头返回值
– 数组需要先知道长度才可以使用,即循环链表得到长度
– 得到长度后需要循环链表给数组元素倒序赋值,最后返回,所以需要定义一个 链表节点赋值head和原head一起完成思路中的两次循环 -
思路二
– 看到倒序,自然联想到栈,循环链表将元素全存入栈中,最后pop到数组中,自然实现从尾到头的返回值数组 -
思路三
– 将链表的反转,后顺序循环存入到数组中。
代码实现
java
思路一
class Solution {
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode node = head;
while(node != null){
node = node.next;
count++;
}
int[] arr = new int[count];
for(int i=1; i<=count; i++){
arr[count-i] = head.val;
head = head.next;
}
return arr;
}
}
思路二
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList();
int count = 0;
while(head != null){
stack.push(head.val);
head = head.next;
count++;
}
int[] arry = new int[count];
for(int i=0; i<count; i++){
arry[i] = stack.pop();
}
return arry;
}
}
问题得以解决,如有更好思路欢迎评论,私聊。